Merge pull request #92 from iyzoer/master

Travis tests
This commit is contained in:
Alex Lushpai 2018-06-14 12:41:53 +03:00 committed by GitHub
commit 0dcededd62
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
58 changed files with 4583 additions and 434 deletions

5
.gitignore vendored
View File

@ -3,4 +3,7 @@
*.settings
*.buildpath
*.project
/vendor
/www
/bin
.env

42
.travis.yml Normal file
View File

@ -0,0 +1,42 @@
language: php
sudo: false
php:
- 7.0
- 7.1
env:
global:
- OC_DB_HOSTNAME=localhost
- OC_DB_USERNAME=root
- OC_DB_PASSWORD=root
- OC_DB_DATABASE=tests_opencart
- OC_DB_DRIVER=mysqli
- OC_USERNAME=admin
- OC_PASSWORD=admin
- OC_EMAIL=test@test.com
- SERVER_PORT=8000
- SERVER_URL=http://localhost
before_script:
# Change MySQL root password
- echo "USE mysql;\nUPDATE user SET password=PASSWORD('root') WHERE user='root';\nFLUSH PRIVILEGES;\n" | mysql -u root
- composer install
- composer setup
- bin/robo project:deploy
- (php -S localhost:8000 -t www &) 2> /dev/null > /dev/null
- sleep 2
script:
- composer test
deploy:
skip_cleanup: true
provider: script
script: make
on:
php: 7.1
branch: master
condition: "$DEPLOY = true"

View File

@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE

14
Makefile Normal file
View File

@ -0,0 +1,14 @@
FILE = $(TRAVIS_BUILD_DIR)/VERSION
VERSION = `cat $(FILE)`
ARCHIVE_NAME = '/tmp/retailcrm-'$(VERSION)'.zip'
all: build_archive send_to_ftp delete_archive
build_archive:
zip -r $(ARCHIVE_NAME) ./src/*
send_to_ftp:
curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)
delete_archive:
rm -f $(ARCHIVE_NAME)

172
RoboFile.php Normal file
View File

@ -0,0 +1,172 @@
<?php
require_once('vendor/autoload.php');
if (file_exists(__DIR__.'/.env')) {
Dotenv::load(__DIR__);
}
class RoboFile extends \Robo\Tasks
{
use \Robo\Task\Development\loadTasks;
use \Robo\Common\TaskIO;
/**
* @var array
*/
private $opencart_config;
/**
* @var int
*/
private $server_port = 80;
/**
* @var string
*/
private $server_url = 'http://localhost';
public function __construct()
{
if ($_ENV) {
foreach ($_ENV as $option => $value) {
if (substr($option, 0, 3) === 'OC_') {
$option = strtolower(substr($option, 3));
$this->opencart_config[$option] = $value;
} elseif ($option === 'SERVER_PORT') {
$this->server_port = (int) $value;
} elseif ($option === 'SERVER_URL') {
$this->server_url = $value;
}
}
} else {
$this->opencart_config = [
'db_hostname' => getenv('OC_DB_HOSTNAME'),
'db_username' => getenv('OC_DB_USERNAME'),
'db_password' => getenv('OC_DB_PASSWORD'),
'db_database' => getenv('OC_DB_DATABASE'),
'db_driver' => getenv('OC_DB_DRIVER'),
'username' => getenv('OC_USERNAME'),
'password' => getenv('OC_PASSWORD'),
'email' => getenv('OC_EMAIL')
];
}
$this->opencart_config['http_server'] = $this->server_url.':'.$this->server_port.'/';
$required = array('db_username', 'password', 'email');
$missing = array();
foreach ($required as $config) {
if (empty($this->opencart_config[$config])) {
$missing[] = 'OC_'.strtoupper($config);
}
}
if (!empty($missing)) {
$this->printTaskError("<error> Missing ".implode(', ', $missing));
$this->printTaskError("<error> See .env.sample ");
die();
}
}
public function opencartSetup()
{
$this->taskDeleteDir('www')->run();
$this->taskFileSystemStack()
->mirror('vendor/opencart/opencart/upload', 'www')
->copy('vendor/beyondit/opencart-test-suite/src/upload/system/config/test-config.php','www/system/config/test-config.php')
->copy('vendor/beyondit/opencart-test-suite/src/upload/catalog/controller/startup/test_startup.php','www/catalog/controller/startup/test_startup.php')
->chmod('www', 0777, 0000, true)
->run();
// Create new database, drop if exists already
try {
$conn = new PDO("mysql:host=".$this->opencart_config['db_hostname'], $this->opencart_config['db_username'], $this->opencart_config['db_password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("DROP DATABASE IF EXISTS `" . $this->opencart_config['db_database'] . "`");
$conn->exec("CREATE DATABASE `" . $this->opencart_config['db_database'] . "`");
}
catch(PDOException $e)
{
$this->printTaskError("<error> Could not connect ot database...");
}
$install = $this->taskExec('php')->arg('www/install/cli_install.php')->arg('install');
foreach ($this->opencart_config as $option => $value) {
$install->option($option, $value);
}
$install->run();
$this->taskDeleteDir('www/install')->run();
$this->restoreSampleData($conn);
$conn = null;
}
public function opencartRun()
{
$this->taskServer($this->server_port)
->dir('www')
->run();
}
public function projectDeploy()
{
$this->taskFileSystemStack()
->mirror('src/upload', 'www')
// ->copy('src/install.xml','www/system/install.ocmod.xml') if exist modification for OCMOD
->run();
}
public function projectWatch()
{
$this->projectDeploy();
$this->taskWatch()
->monitor('composer.json', function () {
$this->taskComposerUpdate()->run();
$this->projectDeploy();
})->monitor('src/', function () {
$this->projectDeploy();
})->run();
}
public function projectPackage()
{
$this->taskDeleteDir('target')->run();
$this->taskFileSystemStack()->mkdir('target')->run();
$zip = new ZipArchive();
$filename = "target/build.ocmod.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
$this->printTaskError("<error> Could not create ZipArchive");
exit();
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator("src", \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->isReadable()) {
$zip->addFile($file->getPathname(),substr($file->getPathname(),4));
}
}
$zip->close();
}
private function restoreSampleData($conn)
{
$sql = file_get_contents('tests/opencart_sample_data.sql');
$conn->exec("USE " . $this->opencart_config['db_database']);
foreach (explode(";\n", $sql) as $sql) {
$sql = trim($sql);
if ($sql) {
$conn->exec($sql);
}
}
}
}

1
VERSION Normal file
View File

@ -0,0 +1 @@
3.0.4

36
composer.json Normal file
View File

@ -0,0 +1,36 @@
{
"name": "retailcrm/opencart-module",
"description": "Integration module for Opencart & RetailCRM",
"license": "GPL-3.0",
"type": "project",
"authors": [
{
"name": "RetailDriverLLC",
"email": "integration@retailcrm.ru"
}
],
"require-dev": {
"opencart/opencart" : "2.3.0.2",
"vlucas/phpdotenv": "~1.1.0",
"phpunit/phpunit" : "~4.0",
"beyondit/opencart-test-suite": "~2.3.0",
"consolidation/robo": "~1",
"henrikbjorn/lurker": "^1.2"
},
"config": {
"bin-dir": "bin/",
"preferred-install": "source"
},
"extra": {
"opencart-dir" : "www"
},
"scripts" : {
"test-admin": "bin/phpunit --testsuite admin-tests --colors=always",
"test-catalog": "bin/phpunit --testsuite catalog-tests --colors=always",
"test": [
"@test-admin",
"@test-catalog"
],
"setup" : "bin/robo opencart:setup"
}
}

3197
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

23
phpunit.xml.dist Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="catalog-tests">
<directory suffix="CatalogTest.php">./tests/catalog/</directory>
</testsuite>
<testsuite name="admin-tests">
<directory suffix="AdminTest.php">./tests/admin/</directory>
</testsuite>
</testsuites>
<php>
<env name="OC_ROOT" value="./www/" />
</php>
</phpunit>

View File

@ -12,7 +12,7 @@
class ControllerExtensionModuleRetailcrm extends Controller
{
private $_error = array();
protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient;
protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle;
public $children, $template;
public function __construct($registry)
@ -20,6 +20,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->tokenTitle = $this->retailcrm->getTokenTitle();
}
/**
@ -31,12 +32,13 @@ class ControllerExtensionModuleRetailcrm extends Controller
{
$this->load->model('setting/setting');
$this->model_setting_setting
->editSetting($this->moduleTitle, array(
$this->moduleTitle . '_status' => 1,
$this->moduleTitle . '_country' => array($this->config->get('config_country_id'))
)
);
$this->model_setting_setting->editSetting(
$this->moduleTitle,
array(
$this->moduleTitle . '_status' => 1,
$this->moduleTitle . '_country' => array($this->config->get('config_country_id'))
)
);
$this->addEvents();
}
@ -50,8 +52,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
{
$this->uninstall_collector();
$this->load->model('setting/setting');
$this->model_setting_setting
->editSetting($this->moduleTitle, array($this->moduleTitle . '_status' => 0));
$this->model_setting_setting->editSetting(
$this->moduleTitle,
array($this->moduleTitle . '_status' => 0)
);
$this->model_setting_setting->deleteSetting('retailcrm_history');
$this->deleteEvents();
}
@ -99,7 +103,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
$tokenTitle = $this->retailcrm->getTokenTitle();
$collector = $this->getCollectorTitle();
$history_setting = $this->model_setting_setting->getSetting('retailcrm_history');
@ -111,21 +114,23 @@ class ControllerExtensionModuleRetailcrm extends Controller
$analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics');
if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1 &&
!in_array($collector, $analytics)) {
if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1
&& !in_array($collector, $analytics)
) {
$this->install_collector();
} elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0 &&
in_array($collector, $analytics)) {
} elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0
&& in_array($collector, $analytics)
) {
$this->uninstall_collector();
}
if (parse_url($this->request->post[$this->moduleTitle . '_url'])) {
$crm_url = parse_url($this->request->post[$this->moduleTitle . '_url'], PHP_URL_HOST);
$this->request->post[$this->moduleTitle . '_url'] = 'https://'.$crm_url;
$this->request->post[$this->moduleTitle . '_url'] = 'https://' . $crm_url;
}
if (isset($this->request->post[$this->moduleTitle . '_custom_field_active']) &&
$this->request->post[$this->moduleTitle . '_custom_field_active'] == 0
if (isset($this->request->post[$this->moduleTitle . '_custom_field_active'])
&& $this->request->post[$this->moduleTitle . '_custom_field_active'] == 0
) {
unset($this->request->post[$this->moduleTitle . '_custom_field']);
}
@ -181,7 +186,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->session->data['success'] = $this->language->get('text_success');
$redirect = $this->url->link(
'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle],
'extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle],
'SSL'
);
@ -311,7 +316,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('text_home'),
'href' => $this->url->link(
'common/home',
$tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL'
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
),
'separator' => false
);
@ -320,7 +325,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('text_module'),
'href' => $this->url->link(
'extension/extension/module',
$tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL'
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
),
'separator' => ' :: '
);
@ -329,19 +334,19 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('retailcrm_title'),
'href' => $this->url->link(
'extension/module/retailcrm',
$tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL'
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
),
'separator' => ' :: '
);
$_data['action'] = $this->url->link(
'extension/module/retailcrm',
$tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL'
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
);
$_data['cancel'] = $this->url->link(
version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension',
$tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL'
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
);
$_data['modules'] = array();
@ -360,7 +365,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['footer'] = $this->load->controller('common/footer');
$_data['countries'] = $this->model_localisation_country->getCountries();
$_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG;
$_data[$tokenTitle] = $this->request->get[$tokenTitle];
$_data[$this->tokenTitle] = $this->request->get[$this->tokenTitle];
if(file_exists(DIR_SYSTEM . '/cron/export_done')) {
$_data['export_file'] = false;
@ -393,8 +398,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['logs']['oc_error'] = $this->language->get('text_error_log');
}
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true);
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $tokenTitle . '=' . $this->session->data[$tokenTitle], true);
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
$_data['button_clear'] = $this->language->get('button_clear');
$this->response->setOutput(
@ -416,18 +421,18 @@ class ControllerExtensionModuleRetailcrm extends Controller
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->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->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');
$this->model_extension_retailcrm_custom_history_v4_5->request();
$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->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient());
}
}
}
@ -448,35 +453,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
}
}
/**
* Create order on event
*
* @param int $order_id order identificator
*
* @return void
*/
public function order_create($order_id)
{
$this->load->model('checkout/order');
$this->load->model('account/order');
$data = $this->model_checkout_order->getOrder($order_id);
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting('retailcrm');
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']);
}
}
/**
* Update customer on event
*
* @param int $customer_id customer identificator
* @param string $route
* @param int $customer customer identificator
*
* @return void
*/
@ -508,7 +489,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
}
$this->load->model('extension/retailcrm/customer');
$this->model_extension_retailcrm_customer->changeInCrm($customer);
$this->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrm->getApiClient());
}
/**
@ -525,13 +506,17 @@ class ControllerExtensionModuleRetailcrm extends Controller
$data['products'] = $this->model_sale_order->getOrderProducts($order_id);
$data['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']);
}
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');
$response = $this->model_extension_retailcrm_order->uploadOrder($data);
$response = $this->model_extension_retailcrm_order->uploadOrder($data, $this->retailcrm->getApiClient());
}
if (!$response->isSuccessful()) {
@ -550,7 +535,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
)
);
} else {
$this->response->setOutPut(
$this->response->setOutput(
json_encode(
array(
'status_code' => $response->getStatusCode()
@ -568,31 +553,30 @@ class ControllerExtensionModuleRetailcrm extends Controller
public function export()
{
$this->load->model('customer/customer');
$customers = $this->model_customer_customer->getCustomers();
$this->load->model('extension/retailcrm/customer');
$this->model_extension_retailcrm_customer->uploadToCrm($customers);
$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());
$orders = $this->model_sale_order->getOrders();
$fullOrders = array();
foreach($orders as $order) {
foreach ($orders as $order) {
$fullOrder = $this->model_sale_order->getOrder($order['order_id']);
$fullOrder['order_total'] = $this->model_sale_order->getOrderTotals($order['order_id']);
$fullOrder['totals'] = $this->model_sale_order->getOrderTotals($order['order_id']);
$fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']);
foreach($fullOrder['products'] as $key=>$product) {
foreach($fullOrder['products'] as $key => $product) {
$fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']);
}
$fullOrders[] = $fullOrder;
}
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->uploadToCrm($fullOrders);
$this->model_extension_retailcrm_order->uploadToCrm($fullOrders, $this->retailcrm->getApiClient());
fopen(DIR_SYSTEM . '/cron/export_done', "x");
}
@ -608,10 +592,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) {
$this->load->model('extension/retailcrm/custom/prices');
$this->model_extension_retailcrm_custom_prices->uploadPrices($products);
$this->model_extension_retailcrm_custom_prices->uploadPrices($products, $this->retailcrm->getApiClient());
} else {
$this->load->model('extension/retailcrm/prices');
$this->model_extension_retailcrm_prices->uploadPrices($products);
$this->model_extension_retailcrm_prices->uploadPrices($products, $this->retailcrm->getApiClient());
}
}
@ -672,8 +656,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/
public function clear_retailcrm()
{
$tokenTitle = $this->getTokenTitle();
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$file = DIR_LOGS . 'retailcrm.log';
@ -682,7 +664,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true));
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
}
/**
@ -692,8 +674,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/
public function clear_opencart()
{
$tokenTitle = $this->getTokenTitle();
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$file = DIR_LOGS . 'opencartapi.log';
@ -702,11 +682,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true));
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
}
/**
* Method for load modelds
* Method for load models
*
* @return void
*/
@ -829,7 +809,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
private function checkEvents()
{
$events = $this->{'model_' . $this->modelEvent}->getEvent(
'retailcrm',
$this->moduleTitle,
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);

View File

@ -1,8 +1,8 @@
<?php
// Heading Goes here:
$_['heading_title'] = 'RetailCRM';
$_['retailcrm_title'] = 'RetailCRM';
$_['heading_title'] = 'Retailcrm';
$_['retailcrm_title'] = 'Retailcrm';
// Text
$_['text_module'] = 'Modules';

View File

@ -1,8 +1,8 @@
<?php
// Heading Goes here:
$_['heading_title'] = 'RetailCRM';
$_['retailcrm_title'] = 'RetailCRM';
$_['heading_title'] = 'Retailcrm';
$_['retailcrm_title'] = 'Retailcrm';
// Text
$_['text_module'] = 'Модули';

View File

@ -13,20 +13,20 @@ class ModelExtensionRetailcrmCustomer extends Model {
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Upload customers
*
* @param array $customers
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return void
* @return mixed
*/
public function uploadToCrm($customers)
public function uploadToCrm($customers, $retailcrmApiClient)
{
if ($this->retailcrmApiClient === false || empty($customers)) {
return;
if ($retailcrmApiClient === false || empty($customers)) {
return false;
}
$customersToCrm = array();
@ -38,26 +38,31 @@ class ModelExtensionRetailcrmCustomer extends Model {
$chunkedCustomers = array_chunk($customersToCrm, 50);
foreach($chunkedCustomers as $customersPart) {
$this->retailcrmApiClient->customersUpload($customersPart);
$retailcrmApiClient->customersUpload($customersPart);
}
return $chunkedCustomers;
}
/**
* Edit customer
*
* @param array $customer
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return void
* @return mixed
*/
public function changeInCrm($customer)
public function changeInCrm($customer, $retailcrmApiClient)
{
if ($this->retailcrmApiClient === false || empty($customer)) {
return;
if ($retailcrmApiClient === false || empty($customer)) {
return false;
}
$customerToCrm = $this->process($customer);
$this->retailcrmApiClient->customersEdit($customerToCrm);
$retailcrmApiClient->customersEdit($customerToCrm);
return $customerToCrm;
}
/**
@ -69,7 +74,6 @@ class ModelExtensionRetailcrmCustomer extends Model {
*/
private function process($customer)
{
$customerToCrm = array(
'externalId' => $customer['customer_id'],
'firstName' => $customer['firstname'],

View File

@ -66,7 +66,7 @@ class ModelExtensionRetailcrmHistory extends Model
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'] . "'");
$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();

View File

@ -6,14 +6,14 @@ class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
{
protected $createResult;
private $opencartApiClient;
/**
* Getting changes from RetailCRM
*
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return boolean
*/
public function request()
public function request($retailcrmApiClient)
{
$moduleTitle = $this->retailcrm->getModuleTitle();
$this->load->model('setting/setting');
@ -40,18 +40,11 @@ class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
return false;
}
$crm = new RetailcrmProxy(
$settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion']
);
$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 = $crm->ordersHistory($lastRun);
$packsOrders = $retailcrmApiClient->ordersHistory($lastRun);
if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) {
return false;
@ -96,14 +89,14 @@ class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
unset($orders);
if (!empty($newOrders)) {
$orders = $crm->ordersList($filter = array('ids' => $newOrders));
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
if ($orders) {
$this->createResult = $this->createOrders($orders['orders']);
}
}
if (!empty($updatedOrders)) {
$orders = $crm->ordersList($filter = array('ids' => $updatedOrders));
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
if ($orders) {
$this->updateOrders($orders['orders']);
}
@ -112,11 +105,13 @@ class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
$this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history_datetime' => $generatedAt));
if (!empty($this->createResult['customers'])) {
$crm->customersFixExternalIds($this->createResult['customers']);
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
}
if (!empty($this->createResult['orders'])) {
$crm->ordersFixExternalIds($this->createResult['orders']);
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
}
return true;
}
}

View File

@ -7,8 +7,8 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
protected $createResult;
protected $settings;
protected $moduleTitle;
protected $opencartApiClient;
private $opencartApiClient;
private $customFieldSetting;
public function __construct($registry)
@ -21,13 +21,13 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
/**
* Getting changes from RetailCRM
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return boolean
*/
public function request()
public function request($retailcrmApiClient)
{
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
@ -52,22 +52,13 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
return false;
}
$this->opencartApiClient = new OpencartApiClient($this->registry);
$crm = new RetailcrmProxy(
$settings[$this->moduleTitle . '_url'],
$settings[$this->moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$this->moduleTitle . '_apiversion']
);
$sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null;
$sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null;
$packsOrders = $crm->ordersHistory(array(
$packsOrders = $retailcrmApiClient->ordersHistory(array(
'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
), 1, 100);
$packsCustomers = $crm->customersHistory(array(
$packsCustomers = $retailcrmApiClient->customersHistory(array(
'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
), 1, 100);
@ -150,21 +141,21 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
unset($customers);
if (!empty($updateCustomers)) {
$customers = $crm->customersList($filter = array('ids' => $updateCustomers));
$customers = $retailcrmApiClient->customersList($filter = array('ids' => $updateCustomers));
if ($customers) {
$this->updateCustomers($customers['customers']);
}
}
if (!empty($newOrders)) {
$orders = $crm->ordersList($filter = array('ids' => $newOrders));
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
if ($orders) {
$this->createResult = $this->createOrders($orders['orders']);
}
}
if (!empty($updatedOrders)) {
$orders = $crm->ordersList($filter = array('ids' => $updatedOrders));
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
if ($orders) {
$this->updateOrders($orders['orders']);
}
@ -180,12 +171,14 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
);
if (!empty($this->createResult['customers'])) {
$crm->customersFixExternalIds($this->createResult['customers']);
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
}
if (!empty($this->createResult['orders'])) {
$crm->ordersFixExternalIds($this->createResult['orders']);
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
}
return true;
}
/**
@ -394,6 +387,7 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
}
$product = $this->model_catalog_product->getProduct($productId);
$rewards = $this->model_catalog_product->getProductRewards($productId);
$data['order_product'][] = array(
'name' => $product['name'],
@ -402,7 +396,8 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
'option' => $options,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}
@ -711,6 +706,7 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
}
$product = $this->model_catalog_product->getProduct($productId);
$rewards = $this->model_catalog_product->getProductRewards($productId);
$data['order_product'][] = array(
'name' => $product['name'],
@ -719,7 +715,8 @@ class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
'option' => $options,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}

View File

@ -13,53 +13,56 @@ class ModelExtensionRetailcrmOrder extends Model {
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Upload orders to CRM
*
* @param array $orders
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return void
* @return mixed
*/
public function uploadToCrm($orders)
public function uploadToCrm($orders, $retailcrmApiClient)
{
if ($this->retailcrmApiClient === false) {
return;
if ($retailcrmApiClient === false) {
return false;
}
$ordersToCrm = array();
foreach($orders as $order) {
foreach ($orders as $order) {
$ordersToCrm[] = $this->process($order);
}
$chunkedOrders = array_chunk($ordersToCrm, 50);
foreach($chunkedOrders as $ordersPart) {
$this->retailcrmApiClient->ordersUpload($ordersPart);
$retailcrmApiClient->ordersUpload($ordersPart);
}
return $chunkedOrders;
}
/**
* Send one order by id
*
* @param array $order_data
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return object $result
* @return mixed
*/
public function uploadOrder($order_data)
public function uploadOrder($order_data, $retailcrmApiClient)
{
if ($this->retailcrmApiClient === false) {
return;
if ($retailcrmApiClient === false) {
return false;
}
if(isset($this->request->post['fromApi'])) {
return;
if (isset($this->request->post['fromApi'])) {
return false;
}
$customers = $this->retailcrmApiClient->customersList(
$customers = $retailcrmApiClient->customersList(
array(
'name' => $order_data['telephone'],
'email' => $order_data['email']
@ -78,13 +81,9 @@ class ModelExtensionRetailcrmOrder extends Model {
unset($customers);
$result = $this->retailcrmApiClient->ordersCreate($order);
$retailcrmApiClient->ordersCreate($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) {
$this->createPayment($order_data, $order_data['order_id']);
}
return $result;
return $order;
}
/**
@ -98,7 +97,6 @@ class ModelExtensionRetailcrmOrder extends Model {
$order = array();
$this->load->model('catalog/product');
$payment_code = $order_data['payment_code'];
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']];
@ -124,7 +122,7 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['phone'] = $order_data['telephone'];
$order['customerComment'] = $order_data['comment'];
if(!empty($order_data['email'])) {
if (!empty($order_data['email'])) {
$order['email'] = $order_data['email'];
}
@ -149,15 +147,13 @@ class ModelExtensionRetailcrmOrder extends Model {
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
$order['delivery'] = array(
'code' => $delivery_code,
'code' => isset($delivery_code) ? $delivery_code : '',
'cost' => $deliveryCost,
'address' => array(
'index' => $order_data['shipping_postcode'],
'city' => $order_data['shipping_city'],
'country' => $order_data['shipping_country_id'],
'region' => $order_data['shipping_zone_id'],
'region' => $order_data['shipping_zone'],
'text' => implode(', ', array(
$order_data['shipping_postcode'],
$country,
@ -174,7 +170,7 @@ class ModelExtensionRetailcrmOrder extends Model {
foreach ($orderProducts as $product) {
$offerId = '';
if(!empty($product['option'])) {
if (!empty($product['option'])) {
$options = array();
$productOptions = $this->model_catalog_product->getProductOptions($product['product_id']);
@ -188,7 +184,7 @@ class ModelExtensionRetailcrmOrder extends Model {
);
}
if(!in_array($option['type'], $offerOptions)) continue;
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) {
@ -250,7 +246,7 @@ class ModelExtensionRetailcrmOrder extends Model {
$customFields = json_decode($order_data['custom_field']);
foreach ($customFields as $key => $value) {
if (isset($this->settings[$moduleTitle . '_custom_field']['o_' . $key])) {
if (isset($this->settings[$this->moduleTitle . '_custom_field']['o_' . $key])) {
$customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['o_' . $key]] = $value;
}
}
@ -262,35 +258,4 @@ class ModelExtensionRetailcrmOrder extends Model {
return $order;
}
/**
* Create payment
*
* @param array $order
* @param int $order_id
*
* @return void
*/
protected function createPayment($order, $order_id)
{
$payment_code = $order['payment_code'];
foreach ($order['totals'] as $total) {
if ($total['code'] == 'total') {
$amount = $total['value'];
}
}
$payment = array(
'externalId' => $order_id,
'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code],
'amount' => $amount
);
$payment['order'] = array(
'externalId' => $order_id
);
$this->retailcrmApiClient->ordersPaymentCreate($payment);
}
}

View File

@ -2,7 +2,6 @@
class ModelExtensionRetailcrmPrices extends Model
{
protected $retailcrmApiClient;
protected $settings;
protected $moduleTitle;
private $options;
@ -22,25 +21,30 @@ class ModelExtensionRetailcrmPrices extends Model
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Upload prices to CRM
*
* @param array $products
*
* @return void
* @param \RetailcrmProxy $retailcrmApiClient
* @return mixed bool | array
*/
public function uploadPrices($products)
public function uploadPrices($products, $retailcrmApiClient)
{
$prices = $this->getPrices($products);
$prices = $this->getPrices($products, $retailcrmApiClient);
if ($retailcrmApiClient === false || !$prices) {
return false;
}
$pricesUpload = array_chunk($prices, 250);
foreach ($pricesUpload as $priceUpload) {
$this->retailcrmApiClient->storePricesUpload($priceUpload);
$retailcrmApiClient->storePricesUpload($priceUpload);
}
return $pricesUpload;
}
/**
@ -48,17 +52,17 @@ class ModelExtensionRetailcrmPrices extends Model
*
* @param array $products
*
* @return array $prices
* @return mixed
*/
protected function getPrices($products)
protected function getPrices($products, $retailcrmApiClient)
{
$prices = array();
$site = $this->getSite();
$site = $this->getSite($retailcrmApiClient);
if (!isset($this->settings[$this->moduleTitle . '_special'])
|| $this->settings[$this->moduleTitle . '_apiversion'] == 'v3'
) {
return;
return false;
}
foreach ($products as $product) {
@ -183,11 +187,13 @@ class ModelExtensionRetailcrmPrices extends Model
/**
* Get site
*
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return mixed boolean | string
*/
private function getSite()
private function getSite($retailcrmApiClient)
{
$response = $this->retailcrmApiClient->sitesList();
$response = $retailcrmApiClient->sitesList();
if ($response && $response->isSuccessful()) {
$sites = $response->sites;

View File

@ -13,11 +13,13 @@ class ControllerApiRetailcrm extends Controller
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country'];
$setting = $this->model_setting_setting->getSetting($moduleTitle);
$response = array();
foreach ($countries as $country) {
$response = array_merge($response, $this->getDeliveryTypesByZones($country));
if (isset($setting[$moduleTitle . '_country']) && $setting[$moduleTitle . '_country']) {
foreach ($setting[$moduleTitle . '_country'] as $country) {
$response = array_merge($response, $this->getDeliveryTypesByZones($country));
}
}
}
@ -145,20 +147,16 @@ class ControllerApiRetailcrm extends Controller
if ( version_compare(VERSION, '3.0', '<')) {
$api = $this->model_account_api->getApiByKey($this->request->get['key']);
} else {
$api = $this->model_account_api->login($this->request->get['username'], $this->request->get['key']);
if (empty($api)) {
$this->load->model('extension/retailcrm/api');
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
}
$this->load->model('extension/retailcrm/api');
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
}
if (!empty($api)) {
return $api;
}
return array('error' => 'Invalid api key');
}
return array('error' => 'Invalid api key');
}
private function loadModels()

View File

@ -7,49 +7,63 @@
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion3
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion5
*/
class ControllerExtensionModuleRetailcrm extends Controller
{
class ControllerExtensionModuleRetailcrm extends Controller {
private $retailcrmApiClient;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Create order on event
*
* @param string $trigger
* @param array $data
* @param int $order_id order identificator
*
* @return void
*/
public function order_create($parameter1, $parameter2 = null, $parameter3 = null)
{
public function order_create($trigger, $data, $order_id = null) {
$this->load->model('checkout/order');
$this->load->model('account/order');
$this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$order_id = $parameter3;
$data = $this->model_checkout_order->getOrder($order_id);
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
$data = $this->model_checkout_order->getOrder($order_id);;
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
foreach($data['products'] as $key => $product) {
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
$moduleTitle = $this->retailcrm->getModuleTitle();
foreach ($data['products'] as $key => $product) {
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
if(!empty($productOptions))
if (!empty($productOptions)) {
$data['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) {
if (isset($data['order_status_id']) && $data['order_status_id'] > 0) {
$data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']];
}
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
$this->load->model('extension/retailcrm/custom/order');
$this->model_extension_retailcrm_custom_order->sendToCrm($data, $data['order_id']);
$order = $this->model_extension_retailcrm_custom_order->processOrder($data);
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient);
} else {
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']);
$order = $this->model_extension_retailcrm_order->processOrder($data);
$this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient);
}
}
}
@ -57,11 +71,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Update order on event
*
* @param int $order_id order identificator
* @param string $trigger
* @param array $parameter2
*
* @return void
*/
public function order_edit($parameter1, $parameter2 = null) {
public function order_edit($trigger, $parameter2 = null) {
$order_id = $parameter2[0];
$this->load->model('checkout/order');
@ -71,16 +86,19 @@ class ControllerExtensionModuleRetailcrm extends Controller
$moduleTitle = $this->retailcrm->getModuleTitle();
$data = $this->model_checkout_order->getOrder($order_id);
if($data['order_status_id'] == 0) return;
if ($data['order_status_id'] == 0) {
return;
}
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
foreach($data['products'] as $key => $product) {
foreach ($data['products'] as $key => $product) {
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
if(!empty($productOptions))
if (!empty($productOptions)) {
$data['products'][$key]['option'] = $productOptions;
}
}
if (!isset($data['fromApi'])) {
@ -93,10 +111,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
$this->load->model('extension/retailcrm/custom/order');
$this->model_extension_retailcrm_custom_order->changeInCrm($data, $data['order_id']);
$order = $this->model_extension_retailcrm_custom_order->processOrder($data, false);
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, false);
} else {
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->changeInCrm($data, $data['order_id']);
$order = $this->model_extension_retailcrm_order->processOrder($data, false);
$this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient, false);
}
}
}
@ -132,10 +152,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
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->model_extension_retailcrm_custom_customer->sendToCrm($customer, $this->retailcrmApiClient);
} else {
$this->load->model('extension/retailcrm/customer');
$this->model_extension_retailcrm_customer->sendToCrm($customer);
$this->model_extension_retailcrm_customer->sendToCrm($customer, $this->retailcrmApiClient);
}
}
@ -157,10 +177,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
$this->load->model('extension/retailcrm/custom/customer');
$this->model_extension_retailcrm_custom_customer->changeInCrm($customer);
$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->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrmApiClient);
}
}
}

View File

@ -3,7 +3,6 @@
class ModelExtensionRetailcrmCustomer extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
public function __construct($registry)
{
@ -13,7 +12,6 @@ class ModelExtensionRetailcrmCustomer extends Model {
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
@ -21,17 +19,19 @@ class ModelExtensionRetailcrmCustomer extends Model {
*
* @param array $customer
*
* @return void
* @return mixed
*/
public function sendToCrm($customer)
public function sendToCrm($customer, $retailcrmApiClient)
{
if(empty($customer) || $this->retailcrmApiClient === false) {
if (empty($customer) || $retailcrmApiClient === false) {
return false;
}
$customerToCrm = $this->process($customer);
$this->retailcrmApiClient->customersCreate($customerToCrm);
$retailcrmApiClient->customersCreate($customerToCrm);
return $customerToCrm;
}
/**
@ -39,17 +39,19 @@ class ModelExtensionRetailcrmCustomer extends Model {
*
* @param array $customer
*
* @return void
* @return mixed
*/
public function changeInCrm($customer)
public function changeInCrm($customer, $retailcrmApiClient)
{
if(empty($customer) || $this->retailcrmApiClient === false) {
if (empty($customer) || $retailcrmApiClient === false) {
return false;
}
$customerToCrm = $this->process($customer);
$this->retailcrmApiClient->customersEdit($customerToCrm);
$retailcrmApiClient->customersEdit($customerToCrm);
return $customerToCrm;
}
/**

View File

@ -3,131 +3,66 @@
class ModelExtensionRetailcrmOrder extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
public function __construct($registry)
{
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);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Create order in CRM
*
* @param array $order_data
* @param int $order_id
* @param array $order
* @param \RetailcrmProxy $retailcrmApiClient
* @param bool $create (default = true)
*
* @return void
* @return mixed
*/
public function sendToCrm($order_data, $order_id)
{
if(isset($this->request->post['fromApi']) || $this->retailcrmApiClient === false) {
return;
public function sendToCrm($order, $retailcrmApiClient, $create = true) {
if (isset($this->request->post['fromApi']) || $retailcrmApiClient === false) {
return false;
}
$order = $this->processOrder($order_data, $order_id);
if (!isset($order['customer']['externalId'])) {
$customer = $this->searchCustomer($order['phone'], $order['email'], $retailcrmApiClient);
$customers = $this->retailcrmApiClient->customersList(
array(
'name' => $order_data['telephone'],
'email' => $order_data['email']
),
1,
100
);
if($customers) {
foreach ($customers['customers'] as $customer) {
if ($customer) {
$order['customer']['id'] = $customer['id'];
}
}
unset($customers);
if ($create) {
$retailcrmApiClient->ordersCreate($order);
} else {
$order_payment = reset($order['payments']);
unset($order['payments']);
$response = $retailcrmApiClient->ordersEdit($order);
$response = $this->retailcrmApiClient->ordersCreate($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$this->createPayment($order_data, $order_id);
}
}
/**
* Edit order in CRM
*
* @param array $order_data
* @param int $order_id
*
* @return void
*/
public function changeInCrm($order_data, $order_id)
{
if(isset($this->request->post['fromApi']) || $this->retailcrmApiClient === false) {
return;
}
$order = $this->processOrder($order_data, $order_id);
$customers = $this->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'];
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$this->updatePayment($order_payment, $order['externalId'], $retailcrmApiClient);
}
}
unset($customers);
$response = $this->retailcrmApiClient->ordersEdit($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$response_order = $this->retailcrmApiClient->ordersGet($order_id);
if ($response_order->isSuccessful()) {
$order_info = $response_order['order'];
}
foreach ($order_info['payments'] as $payment_data) {
if (isset($payment_data['externalId']) && $payment_data['externalId'] == $order_id) {
$payment = $payment_data;
}
}
if (isset($payment) && $payment['type'] != $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) {
$response = $this->retailcrmApiClient->ordersPaymentDelete($payment['id']);
if ($response->isSuccessful()) {
$this->createPayment($order_data, $order_id);
}
} elseif (isset($payment) && $payment['type'] == $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) {
$this->editPayment($order_data, $order_id);
}
}
return $order;
}
/**
* Process order
*
* @param array $order_data
* @param int $order_id
* @param bool $create (default = true)
*
* @return array $order
*/
protected function processOrder($order_data, $order_id)
{
public function processOrder($order_data, $create = true) {
$this->load->model('setting/setting');
$this->load->model('catalog/product');
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$order_id = $order_data['order_id'];
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']];
@ -153,7 +88,11 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['phone'] = $order_data['telephone'];
$order['customerComment'] = $order_data['comment'];
if(!empty($order_data['email'])) {
if ($order_data['customer_id']) {
$order['customer']['externalId'] = $order_data['customer_id'];
}
if (!empty($order_data['email'])) {
$order['email'] = $order_data['email'];
}
@ -161,18 +100,18 @@ class ModelExtensionRetailcrmOrder extends Model {
$couponTotal = 0;
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
foreach ($orderTotals as $totals) {
if ($totals['code'] == 'shipping') {
$deliveryCost = $totals['value'];
}
$totals = $this->explodeTotals($orderTotals);
if ($totals['code'] == 'coupon') {
$couponTotal += abs($totals['value']);
}
if (isset($totals['shipping'])) {
$deliveryCost = $totals['shipping'];
}
if ($totals['code'] == 'reward') {
$couponTotal += abs($totals['value']);
}
if (isset($totals['coupon'])) {
$couponTotal += abs($totals['coupon']);
}
if (isset($totals['reward'])) {
$couponTotal += abs($totals['reward']);
}
$order['createdAt'] = $order_data['date_added'];
@ -188,10 +127,10 @@ class ModelExtensionRetailcrmOrder extends Model {
}
}
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
$country = isset($order_data['shipping_country']) ? $order_data['shipping_country'] : '' ;
$order['delivery'] = array(
'code' => $delivery_code,
'code' => isset($delivery_code) ? $delivery_code : '',
'address' => array(
'index' => $order_data['shipping_postcode'],
'city' => $order_data['shipping_city'],
@ -207,7 +146,7 @@ class ModelExtensionRetailcrmOrder extends Model {
)
);
if(!empty($deliveryCost)){
if (!empty($deliveryCost)){
$order['delivery']['cost'] = $deliveryCost;
}
@ -222,7 +161,7 @@ class ModelExtensionRetailcrmOrder extends Model {
$productOptions = $this->model_catalog_product->getProductOptions($product['product_id']);
foreach($product['option'] as $option) {
foreach ($product['option'] as $option) {
if ($option['type'] == 'checkbox') {
$properties[] = array(
'code' => $option['product_option_value_id'],
@ -231,7 +170,7 @@ class ModelExtensionRetailcrmOrder extends Model {
);
}
if(!in_array($option['type'], $offerOptions)) continue;
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) {
@ -246,7 +185,7 @@ class ModelExtensionRetailcrmOrder extends Model {
ksort($options);
$offerId = array();
foreach($options as $optionKey => $optionValue) {
foreach ($options as $optionKey => $optionValue) {
$offerId[] = $optionKey.'-'.$optionValue;
}
$offerId = implode('_', $offerId);
@ -295,64 +234,91 @@ class ModelExtensionRetailcrmOrder extends Model {
}
}
$payment = array(
'externalId' => $order_id,
'type' => $payment_code,
'amount' => $totals['total']
);
if (!$create) {
$payment['order'] = array(
'externalId' => $order_id
);
}
$order['payments'][] = $payment;
return $order;
}
/**
* Create payment
* Update payment in CRM
*
* @param array $order
* @param int $order_id
* @param array $order_payment
* @param int $orderId
*
* @return void
*/
protected function createPayment($order, $order_id)
{
$payment_code = $order['payment_code'];
private function updatePayment($order_payment, $orderId, $retailcrmApiClient) {
$response_order = $retailcrmApiClient->ordersGet($orderId);
foreach ($order['totals'] as $total) {
if ($total['code'] == 'total') {
$amount = $total['value'];
if ($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;
}
}
$payment = array(
'externalId' => $order_id,
'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code],
'amount' => $amount
if (isset($payment) && $payment['type'] != $order_payment['type']) {
$response = $retailcrmApiClient->ordersPaymentDelete($payment['id']);
if ($response->isSuccessful()) {
$retailcrmApiClient->ordersPaymentCreate($order_payment);
}
} elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
$retailcrmApiClient->ordersPaymentEdit($order_payment);
}
}
private function searchCustomer($phone, $email, $retailcrmApiClient) {
$customer = array();
$response = $retailcrmApiClient->customersList(
array(
'name' => $phone,
'email' => $email
),
1,
100
);
$payment['order'] = array(
'externalId' => $order_id
);
if ($response->isSuccessful() && isset($response['customers'])) {
$customers = $response['customers'];
$this->retailcrmApiClient->ordersPaymentCreate($payment);
if ($customers) {
$customer = end($customers);
}
}
return $customer;
}
/**
* Edit payment
* @param $totals
*
* @param array $order
* @param int $order_id
*
* @return void
* @return array
*/
protected function editPayment($order, $order_id)
private function explodeTotals($totals)
{
$payment_code = $order['payment_code'];
$resultTotals = array();
foreach ($order['totals'] as $total) {
if ($total['code'] == 'total') {
$amount = $total['value'];
}
foreach ($totals as $total) {
$resultTotals[$total['code']] = $total['value'];
}
$payment = array(
'externalId' => $order_id,
'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code],
'amount' => $amount
);
$this->retailcrmApiClient->ordersPaymentEdit($payment);
return $resultTotals;
}
}

View File

@ -30,8 +30,8 @@ class OpencartApiClient {
$cookieFile = explode("\n", $cookieFile);
$cookies = array();
foreach($cookieFile as $line) {
if(empty($line) OR $line{0} == '#') {
foreach ($cookieFile as $line) {
if (empty($line) OR $line{0} == '#') {
continue;
}

View File

@ -12,6 +12,7 @@ class Retailcrm {
{
$this->registry = $registry;
}
public function __get($name) {
return $this->registry->get($name);
}
@ -32,15 +33,16 @@ class Retailcrm {
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
if ($apiUrl === null && $apiKey === null) {
$apiUrl = $setting[$this->getModuleTitle() . '_url'];
$apiKey = $setting[$this->getModuleTitle() . '_apikey'];
$apiVersion = $setting[$this->getModuleTitle() . '_apiversion'];
$apiUrl = isset($setting[$this->getModuleTitle() . '_url'])
? $setting[$this->getModuleTitle() . '_url'] : '';
$apiKey = isset($setting[$this->getModuleTitle() . '_apikey'])
? $setting[$this->getModuleTitle() . '_apikey'] : '';
$apiVersion = isset($setting[$this->getModuleTitle() . '_apiversion'])
? $setting[$this->getModuleTitle() . '_apiversion'] : '';
}
if ($apiUrl && $apiKey) {
$this->apiClient = new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion);
return $this->apiClient;
return new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion);
}
return false;

View File

@ -0,0 +1,57 @@
<?php
class ControllerRetailcrmAdminTest extends OpenCartTest
{
const MODULE_TITLE = 'retailcrm';
public function setUp()
{
$query = $this->db->query("SELECT permission from ".DB_PREFIX."user_group WHERE name = 'Administrator'");
$permissions = json_decode($query->row['permission'],true);
if (!in_array('extension/module/retailcrm',$permissions['access'])) {
$permissions['access'][] = 'extension/module/retailcrm';
$this->db->query("UPDATE ".DB_PREFIX."user_group SET permission='".$this->db->escape(json_encode($permissions))."' WHERE name = 'Administrator'");
}
$this->retailcrm = $this->getMockBuilder('\retailcrm\Retailcrm')
->disableOriginalConstructor()
->getMock();
}
public function testIndex()
{
$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());
}
}

View File

@ -0,0 +1,59 @@
<?php
class ModelRetailcrmCustomerAdminTest extends OpenCartTest
{
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(
'customersUpload',
'customersEdit'
))
->getMock();
}
public function testUploadToCrm()
{
$customerModel = $this->loadModel('customer/customer');
$customers = $customerModel->getCustomers();
$customersSend = $this->customerModel->uploadToCrm($customers, $this->apiClientMock);
$customer = $customersSend[0][0];
$this->assertInternalType('array', $customersSend);
$this->assertInternalType('array', $customersSend[0]);
$this->assertArrayHasKey('externalId', $customer);
$this->assertArrayHasKey('firstName', $customer);
$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

@ -0,0 +1,185 @@
<?php
class ModelRetailcrmOrderAdminTest extends OpenCartTest
{
private $orderModel;
private $apiClientMock;
private $settingModel;
private $retailcrm;
const CUSTOMER_ID = 1;
const ORDER_WITH_CUST_ID = 1;
const ORDER_ID = 2;
public function setUp()
{
parent::setUp();
$this->orderModel = $this->loadModel('extension/retailcrm/order');
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
->disableOriginalConstructor()
->setMethods(array(
'ordersUpload',
'customersList',
'ordersCreate',
'ordersPaymentCreate'
))
->getMock();
$this->settingModel = $this->loadModel('setting/setting');
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->settingModel->editSetting(
$this->retailcrm->getModuleTitle(),
array(
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
$this->retailcrm->getModuleTitle() . '_status' => array(
1 => 'new'
),
$this->retailcrm->getModuleTitle() . '_delivery' => array(
'flat.flat' => 'flat'
),
$this->retailcrm->getModuleTitle() . '_payment' => array(
'cod' => 'cod'
)
)
);
}
public function testUploadToCrm()
{
$saleOrderModel = $this->loadModel('sale/order');
$orders = $saleOrderModel->getOrders();
$fullOrders = array();
foreach ($orders as $order) {
$fullOrder = $saleOrderModel->getOrder($order['order_id']);
$fullOrder['order_total'] = $saleOrderModel->getOrderTotals($order['order_id']);
$fullOrder['products'] = $saleOrderModel->getOrderProducts($order['order_id']);
foreach($fullOrder['products'] as $key => $product) {
$fullOrder['products'][$key]['option'] = $saleOrderModel->getOrderOptions($product['order_id'], $product['order_product_id']);
}
$fullOrders[] = $fullOrder;
}
$chunkedOrders = $this->orderModel->uploadToCrm($fullOrders, $this->apiClientMock);
$order = $chunkedOrders[0][0];
$this->assertInternalType('array', $chunkedOrders);
$this->assertInternalType('array', $chunkedOrders[0]);
$this->assertNotEmpty($chunkedOrders[0]);
$this->assertArrayHasKey('externalId', $order);
$this->assertArrayHasKey('number', $order);
$this->assertArrayHasKey('firstName', $order);
$this->assertArrayHasKey('lastName', $order);
$this->assertArrayHasKey('email', $order);
$this->assertArrayHasKey('phone', $order);
$this->assertArrayHasKey('createdAt', $order);
$this->assertArrayHasKey('delivery', $order);
$this->assertArrayHasKey('status', $order);
$this->assertArrayHasKey('items', $order);
$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);
$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->assertArrayNotHasKey('customer', $orderSend);
$this->assertNotEmpty($orderSend['payments']);
}
}

View File

@ -0,0 +1,51 @@
<?php
class ModelRetailcrmPricesAdminTest extends OpenCartTest
{
private $pricesModel;
private $apiClientMock;
private $settingModel;
private $retailcrm;
public function setUp()
{
parent::setUp();
$this->pricesModel = $this->loadModel('extension/retailcrm/prices');
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
->disableOriginalConstructor()
->setMethods(array(
'storePricesUpload',
'sitesList'
))
->getMock();
$this->settingModel = $this->loadModel('setting/setting');
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->settingModel->editSetting(
$this->retailcrm->getModuleTitle(),
array(
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
$this->retailcrm->getModuleTitle() . '_special' => 'special'
)
);
}
public function testUploadPrices()
{
$productModel = $this->loadModel('catalog/product');
$products = $productModel->getProducts();
$prices = $this->pricesModel->uploadPrices($products, $this->apiClientMock);
$price = $prices[0][0];
$this->assertInternalType('array', $prices);
$this->assertInternalType('array', $prices[0]);
$this->assertInternalType('array', $price);
$this->assertArrayHasKey('externalId', $price);
$this->assertArrayHasKey('site', $price);
$this->assertArrayHasKey('prices', $price);
$this->assertInternalType('array', $price['prices']);
}
}

View File

@ -0,0 +1,72 @@
<?php
class ControllerRetailcrmApiCatalogTest extends OpenCartTest
{
private $apiKey;
private $retailcrm;
const ORDER_ID = 1;
public function setUp()
{
parent::setUp();
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE api_id = 1");
$api = $query->row;
$this->apiKey = $api['key'];
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->setSetting(
$this->retailcrm->getModuleTitle(),
array(
$this->retailcrm->getModuleTitle() . '_country' => array(1),
)
);
if (isset($this->request->get['key'])) {
unset($this->request->get['key']);
}
}
public function testGetDeliveryTypes()
{
$response = $this->dispatchAction('api/retailcrm/getDeliveryTypes');
$data = json_decode($response->getOutput());
$this->assertEquals('Not found api key', $data->error);
$this->request->get['key'] = $this->apiKey;
$response = $this->dispatchAction('api/retailcrm/getDeliveryTypes');
$data = json_decode($response->getOutput());
$this->assertNotEmpty($data);
}
public function testAddOrderHistory()
{
$response = $this->dispatchAction('api/retailcrm/addOrderHistory');
$data = json_decode($response->getOutput());
$this->assertEquals('Not found api key', $data->error);
$this->request->get['key'] = $this->apiKey;
$response = $this->dispatchAction('api/retailcrm/addOrderHistory');
$data = json_decode($response->getOutput());
$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

@ -0,0 +1,62 @@
<?php
class ModelRetailcrmCustomerCatalogTest extends OpenCartTest
{
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

@ -0,0 +1,191 @@
<?php
class ModelRetailcrmOrderCatalogTest extends OpenCartTest
{
private $orderModel;
private $apiClientMock;
private $retailcrm;
const CUSTOMER_ID = 1;
const ORDER_WITH_CUST_ID = 1;
const ORDER_ID = 2;
public function setUp()
{
parent::setUp();
$this->orderModel = $this->loadModel('extension/retailcrm/order');
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
->disableOriginalConstructor()
->setMethods(array(
'ordersCreate',
'ordersEdit',
'ordersGet',
'ordersPaymentEdit',
'customersList'
))
->getMock();
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->setSetting(
$this->retailcrm->getModuleTitle(),
array(
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
$this->retailcrm->getModuleTitle() . '_status' => array(
1 => 'new'
),
$this->retailcrm->getModuleTitle() . '_delivery' => array(
'flat.flat' => 'flat'
),
$this->retailcrm->getModuleTitle() . '_payment' => array(
'cod' => 'cod'
)
)
);
}
public function testCreateOrderWithCustomer()
{
$orderCheckoutModel = $this->loadModel('checkout/order');
$orderAccountModel = $this->loadModel('account/order');
$order_id = self::ORDER_WITH_CUST_ID;
$order = $orderCheckoutModel->getOrder($order_id);
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
foreach ($order['products'] as $key => $product) {
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
if (!empty($productOptions)) {
$order['products'][$key]['option'] = $productOptions;
}
}
$orderProcess = $this->orderModel->processOrder($order);
$orderSend = $this->orderModel->sendToCrm($orderProcess, $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 testEditOrderWithCustomer()
{
$orderCheckoutModel = $this->loadModel('checkout/order');
$orderAccountModel = $this->loadModel('account/order');
$order_id = self::ORDER_WITH_CUST_ID;
$order = $orderCheckoutModel->getOrder($order_id);
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
foreach ($order['products'] as $key => $product) {
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
if (!empty($productOptions)) {
$order['products'][$key]['option'] = $productOptions;
}
}
$orderEditResponse = new \RetailcrmApiResponse(
200,
json_encode(
array(
'success' => true,
'id' => 1
)
)
);
$ordersGetResponse = new \RetailcrmApiResponse(
200,
json_encode(
array(
'success' => true,
'order' => $this->getOrder($order_id)
)
)
);
$this->apiClientMock->expects($this->any())->method('ordersEdit')->willReturn($orderEditResponse);
$this->apiClientMock->expects($this->any())->method('ordersGet')->willReturn($ordersGetResponse);
$orderProcess = $this->orderModel->processOrder($order);
$orderSend = $this->orderModel->sendToCrm($orderProcess, $this->apiClientMock, false);
$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);
}
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'");
}
}
}
}
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,49 @@
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_customer_activity`;
TRUNCATE TABLE `oc_customer_group`;
INSERT INTO `oc_customer_group` (`customer_group_id`, `approval`, `sort_order`) VALUES ('1', '0', '1');
TRUNCATE TABLE `oc_customer_group_description`;
INSERT INTO `oc_customer_group_description` (`customer_group_id`, `language_id`, `name`, `description`) VALUES ('1', '1', 'Default', 'test');
TRUNCATE TABLE `oc_customer_history`;
TRUNCATE TABLE `oc_customer_ip`;
INSERT INTO `oc_customer_ip` (`customer_ip_id`, `customer_id`, `ip`, `date_added`) VALUES ('4', '1', '172.21.0.1', '2018-06-07 13:50:29');
TRUNCATE TABLE `oc_customer_login`;
TRUNCATE TABLE `oc_customer_online`;
TRUNCATE TABLE `oc_customer_reward`;
TRUNCATE TABLE `oc_customer_search`;
TRUNCATE TABLE `oc_customer_transaction`;
TRUNCATE TABLE `oc_customer_wishlist`;
TRUNCATE TABLE `oc_order`;
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('1', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '1', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', '', '106.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:51:10', '2018-06-07 13:51:23');
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('2', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '[]', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', '', '85.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:53:50', '2018-06-07 13:54:00');
TRUNCATE TABLE `oc_order_custom_field`;
TRUNCATE TABLE `oc_order_history`;
INSERT INTO `oc_order_history` (`order_history_id`, `order_id`, `order_status_id`, `notify`, `comment`, `date_added`) VALUES ('19', '2', '1', '0', '', '2018-06-07 13:54:00');
INSERT INTO `oc_order_history` (`order_history_id`, `order_id`, `order_status_id`, `notify`, `comment`, `date_added`) VALUES ('18', '1', '1', '0', '', '2018-06-07 13:51:23');
TRUNCATE TABLE `oc_order_option`;
INSERT INTO `oc_order_option` (`order_option_id`, `order_id`, `order_product_id`, `product_option_id`, `product_option_value_id`, `name`, `value`, `type`) VALUES ('15', '2', '55', '226', '15', 'Select', 'Red', 'select');
TRUNCATE TABLE `oc_order_product`;
INSERT INTO `oc_order_product` (`order_product_id`, `order_id`, `product_id`, `name`, `model`, `quantity`, `price`, `total`, `tax`, `reward`) VALUES ('54', '1', '40', 'iPhone', 'product 11', '1', '101.0000', '101.0000', '18.0000', '20');
INSERT INTO `oc_order_product` (`order_product_id`, `order_id`, `product_id`, `name`, `model`, `quantity`, `price`, `total`, `tax`, `reward`) VALUES ('55', '2', '30', 'Canon EOS 5D', 'Product 3', '1', '80.0000', '80.0000', '18.0000', '200');
TRUNCATE TABLE `oc_order_recurring`;
TRUNCATE TABLE `oc_order_recurring_transaction`;
TRUNCATE TABLE `oc_order_total`;
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('162', '1', 'shipping', 'Flat Rate', '5.0000', '3');
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('161', '1', 'sub_total', 'Sub-Total', '101.0000', '1');
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('164', '2', 'sub_total', 'Sub-Total', '80.0000', '1');
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('165', '2', 'shipping', 'Flat Rate', '5.0000', '3');
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('163', '1', 'total', 'Total', '106.0000', '9');
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('166', '2', 'total', 'Total', '85.0000', '9');
TRUNCATE TABLE `oc_order_voucher`;