1
0
mirror of synced 2025-02-21 01:13:13 +03:00

Add export functionality

This commit is contained in:
Dima Uryvskiy 2021-07-09 13:46:28 +03:00 committed by GitHub
parent badcc0e38f
commit 5979c7cb0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 717 additions and 260 deletions

View File

@ -271,3 +271,6 @@ msgstr "Se abrirá una ventana de chat con este contacto en WhatsApp"
msgid "Introduce the correct phone number"
msgstr "Introduce el número de teléfono correcto"
msgid "You can export all orders and customers from CMS to Simla.com by clicking the «Upload» button. This process can take much time and before it is completed, you need to keep the tab open."
msgstr "Presionando el botón «Exportar» puedes descargar a todos los pedidos y clientes de CMS a Simla.com. Este proceso puede llevar mucho tiempo y es necesario mantener abierta la pestaña hasta que termine el proceso."

View File

@ -280,3 +280,7 @@ msgstr "Будет открыт чат в WhatsApp с данным контак
msgid "Introduce the correct phone number"
msgstr "Введите корректный номер телефона"
msgid "You can export all orders and customers from CMS to Simla.com by clicking the «Upload» button. This process can take much time and before it is completed, you need to keep the tab open."
msgstr "Вы можете экспортировать все заказы и клиентов из CMS в Simla.com, нажав кнопку «Выгрузить». Этот процесс может занять много времени, и до его завершения необходимо держать вкладку открытой."

View File

@ -0,0 +1,33 @@
.retail-progress {
border-radius: 18px;
border: 1px solid rgba(122, 122, 122, 0.15);
width: 400px;
height: 18px;
overflow: hidden;
transition: height 0.25s ease;
}
.retail-progress__loader {
width: 0;
border-radius: 18px;
background: #6427D6;
color: white;
text-align: center;
padding: 0 30px;
font-size: 18px;
font-weight: 600;
transition: width 0.4s ease-in;
line-height: 18px;
box-sizing: border-box;
}
.retail-hidden {
display: none !important;
}
.retail-count-data-upload {
margin-bottom: 20px;
size: 30px;
color: #6427D6;
font-weight: bold;
}

1
src/assets/css/progress-bar.min.css vendored Normal file
View File

@ -0,0 +1 @@
.retail-progress{border-radius:18px;border:1px solid rgba(122,122,122,0.15);width:400px;height:18px;overflow:hidden;transition:height .25s ease}.retail-progress__loader{width:0;border-radius:18px;background:#6427D6;color:#fff;text-align:center;padding:0 30px;font-size:18px;font-weight:600;transition:width .4s ease-in;line-height:18px;box-sizing:border-box}.retail-hidden{display:none!important}.retail-count-data-upload{margin-bottom:20px;size:30px;color:#6427D6;font-weight:700}

View File

@ -0,0 +1,152 @@
jQuery(function () {
function RetailcrmExportForm()
{
this.submitButton = jQuery('button[id="export-orders-submit"]').get(0);
jQuery(this.submitButton).after('<div id="export-orders-progress" class="retail-progress retail-hidden"></div');
jQuery(this.submitButton).before('<div id="export-orders-count" class="retail-count-data-upload"></div');
this.progressBar = jQuery('div[id="export-orders-progress"]').get(0);
if (typeof this.submitButton === 'undefined') {
return false;
}
if (typeof this.progressBar === 'undefined') {
return false;
}
jQuery(this.submitButton).addClass('retail-hidden');
this.ordersCount = 0;
this.customersCount = 0;
let _this = this;
jQuery.ajax({
url: window.location.origin + '/wp-admin/admin-ajax.php?action=content_upload',
method: "POST",
timeout: 0,
data: {ajax: 1},
dataType: "json"
})
.done(function (response) {
_this.ordersCount = response.count_orders;
_this.customersCount = response.count_users;
jQuery(_this.submitButton).removeClass('retail-hidden');
_this.displayCountUploadData();
})
this.isDone = false;
this.ordersStepSize = 50;
this.customersStepSize = 50;
this.ordersStep = 0;
this.customersStep = 0;
this.displayCountUploadData = this.displayCountUploadData.bind(this);
this.submitAction = this.submitAction.bind(this);
this.exportAction = this.exportAction.bind(this);
this.exportDone = this.exportDone.bind(this);
this.initializeProgressBar = this.initializeProgressBar.bind(this);
this.updateProgressBar = this.updateProgressBar.bind(this);
jQuery(this.submitButton).click(this.submitAction);
}
RetailcrmExportForm.prototype.displayCountUploadData = function () {
this.counter = jQuery('div[id="export-orders-count"]').get(0);
jQuery(this.counter).text('Customers: ' + this.customersCount + ' Orders: ' + this.ordersCount);
}
RetailcrmExportForm.prototype.submitAction = function (event) {
event.preventDefault();
jQuery(this.counter).css("margin-left", "120px");
this.initializeProgressBar();
this.exportAction();
};
RetailcrmExportForm.prototype.exportAction = function () {
let data = {};
if (this.customersStep * this.customersStepSize < this.customersCount) {
data.RETAILCRM_EXPORT_CUSTOMERS_STEP = this.customersStep;
data.Entity = 'customer';
this.customersStep++;
} else {
if (this.ordersStep * this.ordersStepSize < this.ordersCount) {
data.RETAILCRM_EXPORT_ORDERS_STEP = this.ordersStep;
data.Entity = 'order';
this.ordersStep++;
} else {
data.RETAILCRM_UPDATE_SINCE_ID = 1;
this.isDone = true;
}
}
let _this = this;
jQuery.ajax({
url: window.location.origin + '/wp-admin/admin-ajax.php?action=do_upload',
method: "POST",
timeout: 0,
data: data
})
.done(function (response) {
if (_this.isDone) {
return _this.exportDone();
}
_this.updateProgressBar();
_this.exportAction();
})
};
RetailcrmExportForm.prototype.initializeProgressBar = function () {
jQuery(this.submitButton).addClass('retail-hidden');
jQuery(this.progressBar)
.removeClass('retail-hidden')
.append(jQuery('<div/>', {class: 'retail-progress__loader', text: '0%'}))
window.addEventListener('beforeunload', this.confirmLeave);
};
RetailcrmExportForm.prototype.updateProgressBar = function () {
let processedOrders = this.ordersStep * this.ordersStepSize;
if (processedOrders > this.ordersCount) {
processedOrders = this.ordersCount;
}
let processedCustomers = this.customersStep * this.customersStepSize;
if (processedCustomers > this.customersCount) {
processedCustomers = this.customersCount;
}
const processed = processedOrders + processedCustomers;
const total = this.ordersCount + this.customersCount;
const percents = Math.round(100 * processed / total);
jQuery(this.progressBar).find('.retail-progress__loader').text(percents + '%');
jQuery(this.progressBar).find('.retail-progress__loader').css('width', percents + '%');
jQuery(this.progressBar).find('.retail-progress__loader').attr('title', processed + '/' + total);
};
RetailcrmExportForm.prototype.confirmLeave = function (event) {
event.preventDefault();
event.returnValue = 'Export process has been started';
}
RetailcrmExportForm.prototype.exportDone = function () {
window.removeEventListener('beforeunload', this.confirmLeave);
alert('Done');
}
window.RetailcrmExportForm = RetailcrmExportForm;
if (!(typeof RetailcrmExportForm === 'undefined')) {
new window.RetailcrmExportForm();
}
});

View File

@ -23,7 +23,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/**
* WC_Retailcrm_Abstracts_Settings constructor.
*/
public function __construct() {
public function __construct()
{
$this->id = 'integration-retailcrm';
$this->method_title = __('Simla.com', 'retailcrm');
$this->method_description = __('Integration with Simla.com management system.', 'retailcrm');
@ -35,27 +36,40 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
) {
add_action('init', array($this, 'init_settings_fields'), 99);
}
// Include js scripts
$this->includeJsScripts();
// Include css file
$this->includeCssFile();
}//end __construct()
/**
* In this method we include JS scripts.
*
* @return void
*/
private function includeJsScripts()
{
wp_register_script('retailcrm-export', plugins_url() . '/woo-retailcrm/assets/js/retailcrm-export.js');
wp_enqueue_script('retailcrm-export');
}
public function ajax_upload()
/**
* In this method we include CSS file
*
* @return void
*/
private function includeCssFile()
{
$ajax_url = admin_url('admin-ajax.php');
?>
<script type="text/javascript">
jQuery('#uploads-retailcrm').bind('click', function() {
jQuery.ajax({
type: "POST",
url: '<?php echo $ajax_url; ?>?action=do_upload',
success: function (response) {
alert('<?php echo __('Customers and orders were uploaded', 'retailcrm'); ?>');
console.log('AJAX response : ',response);
}
});
});
</script>
<?php
wp_register_style('retailcrm-orders-export', plugins_url() . '/woo-retailcrm/assets/css/progress-bar.min.css', false, '0.1');
wp_enqueue_style('retailcrm-orders-export');
}
public function ajax_generate_icml()
{
$ajax_url = admin_url('admin-ajax.php');
@ -109,7 +123,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
'api_url' => array(
'title' => __( 'API of URL', 'retailcrm' ),
'type' => 'text',
'description' => __( 'Enter API of URL (https://yourdomain.retailcrm.pro).', 'retailcrm' ),
'description' => __( 'Enter API of URL (https://yourdomain.simla.com).', 'retailcrm' ),
'desc_tip' => true,
'default' => ''
),
@ -418,25 +432,21 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/**
* Uploads options
*/
$options = array_filter(get_option(static::$option_key));
$this->form_fields[] = array(
'title' => __('Settings of uploading', 'retailcrm'),
'type' => 'heading',
'description' => '',
'id' => 'upload_options'
);
if (!isset($options['uploads'])) {
$this->form_fields[] = array(
'title' => __('Settings of uploading', 'retailcrm'),
'type' => 'heading',
'description' => '',
'id' => 'upload_options'
);
$this->form_fields['upload-button'] = array(
'label' => __('Upload', 'retailcrm'),
'title' => __('Uploading all customers and orders', 'retailcrm' ),
'type' => 'button',
'description' => __('Uploading the existing customers and orders to Simla.com', 'retailcrm' ),
'desc_tip' => true,
'id' => 'uploads-retailcrm'
);
}
$this->form_fields['upload-button'] = array(
'label' => __('Upload', 'retailcrm'),
'title' => __('Uploading all customers and orders', 'retailcrm'),
'type' => 'button',
'description' => __('You can export all orders and customers from CMS to Simla.com by clicking the «Upload» button. This process can take much time and before it is completed, you need to keep the tab open.', 'retailcrm'),
'desc_tip' => true,
'id' => 'export-orders-submit'
);
/**
* WhatsApp options
@ -636,11 +646,11 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
public function validate_online_assistant_field($key, $value)
{
$onlineAssistant = $_POST['woocommerce_integration-retailcrm_online_assistant'];
if (!empty($onlineAssistant) && is_string($onlineAssistant)) {
return wp_unslash($onlineAssistant);
}
return '';
}
@ -788,4 +798,4 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
)
);
}
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* RetailCRM Integration.
*
@ -38,14 +39,18 @@ if (!class_exists('WC_Retailcrm_Base')) {
/** @var \WC_Retailcrm_Orders */
protected $orders;
/** @var WC_Retailcrm_Uploader */
protected $uploader;
/**
* Init and hook in the integration.
* @param \WC_Retailcrm_Proxy|WC_Retailcrm_Client_V4|WC_Retailcrm_Client_V5|bool $retailcrm (default = false)
*/
public function __construct($retailcrm = false) {
public function __construct($retailcrm = false)
{
parent::__construct();
if (!class_exists( 'WC_Retailcrm_Proxy')) {
if (!class_exists('WC_Retailcrm_Proxy')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('include/api/class-wc-retailcrm-proxy.php'));
}
@ -59,31 +64,33 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->customers = new WC_Retailcrm_Customers(
$this->apiClient,
$this->settings,
new WC_Retailcrm_Customer_Address
new WC_Retailcrm_Customer_Address()
);
$this->orders = new WC_Retailcrm_Orders(
$this->apiClient,
$this->settings,
new WC_Retailcrm_Order_Item($this->settings),
new WC_Retailcrm_Order_Address,
new WC_Retailcrm_Order_Address(),
$this->customers,
new WC_Retailcrm_Order($this->settings),
new WC_Retailcrm_Order_Payment($this->settings)
);
$this->uploader = new WC_Retailcrm_Uploader($this->apiClient, $this->orders, $this->customers);
// Actions.
add_action('woocommerce_update_options_integration_' . $this->id, array($this, 'process_admin_options'));
add_filter('woocommerce_settings_api_sanitized_fields_' . $this->id, array($this, 'api_sanitized'));
add_action('admin_bar_menu', array($this, 'add_retailcrm_button'), 100 );
add_action('admin_bar_menu', array($this, 'add_retailcrm_button'), 100);
add_action('woocommerce_checkout_order_processed', array($this, 'retailcrm_process_order'), 10, 1);
add_action('retailcrm_history', array($this, 'retailcrm_history_get'));
add_action('retailcrm_icml', array($this, 'generate_icml'));
add_action('retailcrm_inventories', array($this, 'load_stocks'));
add_action('wp_ajax_do_upload', array($this, 'upload_to_crm'));
add_action('wp_ajax_content_upload', array($this, 'count_upload_data'), 99);
add_action('wp_ajax_generate_icml', array($this, 'generate_icml'));
add_action('wp_ajax_order_upload', array($this, 'order_upload'));
add_action('admin_print_footer_scripts', array($this, 'ajax_upload'), 99);
add_action('admin_print_footer_scripts', array($this, 'ajax_generate_icml'), 99);
add_action('admin_print_footer_scripts', array($this, 'ajax_selected_order'), 99);
add_action('woocommerce_created_customer', array($this, 'create_customer'), 10, 1);
@ -98,7 +105,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('wp_print_footer_scripts', array($this, 'send_analytics'), 99);
add_action('woocommerce_new_order', array($this, 'create_order'), 11, 1);
if (!$this->get_option('deactivate_update_order')
if (
!$this->get_option('deactivate_update_order')
|| $this->get_option('deactivate_update_order') == static::NO
) {
add_action('woocommerce_update_order', array($this, 'update_order'), 11, 1);
@ -155,7 +163,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
return $settings;
}
public function generate_icml() {
public function generate_icml()
{
/*
* A temporary solution.
* We have rebranded the module and changed the name of the ICML file.
@ -177,14 +186,14 @@ if (!class_exists('WC_Retailcrm_Base')) {
$getSites = $this->apiClient->sitesList();
if (empty($getSites['sites']) === false && $getSites->isSuccessful() === true) {
if(empty($getSites['sites'][$codeSite]) === false) {
if (empty($getSites['sites'][$codeSite]) === false) {
$dataSite = $getSites['sites'][$codeSite];
if (empty($dataSite['ymlUrl']) === false) {
$ymlUrl = $dataSite['ymlUrl'];
if (strpos($ymlUrl, 'simla') === false) {
$ymlUrl = str_replace('/retailcrm.xml', '/simla.xml', $ymlUrl);
$ymlUrl = str_replace('/retailcrm.xml', '/simla.xml', $ymlUrl);
$dataSite['ymlUrl'] = $ymlUrl;
$this->apiClient->sitesEdit($dataSite);
@ -196,14 +205,14 @@ if (!class_exists('WC_Retailcrm_Base')) {
$retailCrmIcml = new WC_Retailcrm_Icml();
$retailCrmIcml->generate();
}
/**
* Get history
*/
public function retailcrm_history_get() {
public function retailcrm_history_get()
{
$retailcrm_history = new WC_Retailcrm_History($this->apiClient);
$retailcrm_history->getHistory();
}
@ -211,53 +220,28 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* @param int $order_id
*/
public function retailcrm_process_order($order_id) {
public function retailcrm_process_order($order_id)
{
$this->orders->orderCreate($order_id);
}
/**
* Load stock from retailCRM
*/
public function load_stocks() {
public function load_stocks()
{
$inventories = new WC_Retailcrm_Inventories($this->apiClient);
$inventories->updateQuantity();
}
/**
* Upload selected orders
*
* @return void
*/
public function order_upload() {
$ids = false;
if (isset($_GET['order_ids_retailcrm'])) {
$appendix = array();
$ids = explode(',', $_GET['order_ids_retailcrm']);
foreach ($ids as $key => $id) {
if (stripos($id, '-') !== false) {
$idSplit = explode('-', $id);
if (count($idSplit) == 2) {
$expanded = array();
$first = (int) $idSplit[0];
$last = (int) $idSplit[1];
for ($i = $first; $i <= $last; $i++) {
$expanded[] = $i;
}
$appendix = array_merge($appendix, $expanded);
unset($ids[$key]);
}
}
}
$ids = array_unique(array_merge($ids, $appendix));
}
if ($ids) {
$this->orders->ordersUpload($ids);
}
public function order_upload()
{
$this->uploader->uploadSelectedOrders();
}
/**
@ -265,13 +249,14 @@ if (!class_exists('WC_Retailcrm_Base')) {
*/
public function upload_to_crm()
{
$options = array_filter(get_option(static::$option_key));
$page = filter_input(INPUT_POST, 'RETAILCRM_EXPORT_ORDERS_STEP');
$entity = filter_input(INPUT_POST, 'Entity');
$this->customers->customersUpload();
$this->orders->ordersUpload();
$options['uploads'] = static::YES;
update_option(static::$option_key, $options);
if ($entity === 'customer') {
$this->uploader->uploadArchiveCustomers($page);
} else {
$this->uploader->uploadArchiveOrders($page);
}
}
/**
@ -288,40 +273,41 @@ if (!class_exists('WC_Retailcrm_Base')) {
return;
}
$client = $this->getApiClient();
$client = $this->getApiClient();
if (empty($client)) {
return;
}
$wcCustomer = new WC_Customer($customer_id);
$email = $wcCustomer->get_billing_email();
if (empty($email)) {
$email = $wcCustomer->get_email();
if (empty($client)) {
return;
}
if (empty($email)) {
return;
$wcCustomer = new WC_Customer($customer_id);
$email = $wcCustomer->get_billing_email();
if (empty($email)) {
$email = $wcCustomer->get_email();
}
if (empty($email)) {
return;
} else {
$wcCustomer->set_billing_email($email);
$wcCustomer->save();
$wcCustomer->set_billing_email($email);
$wcCustomer->save();
}
$response = $client->customersList(array('email' => $email));
$response = $client->customersList(array('email' => $email));
if (!empty($response)
if (
!empty($response)
&& $response->isSuccessful()
&& isset($response['customers'])
&& count($response['customers']) > 0
) {
$customers = $response['customers'];
$customer = reset($customers);
$customers = $response['customers'];
$customer = reset($customers);
if (isset($customer['id'])) {
$this->customers->updateCustomerById($customer_id, $customer['id']);
$builder = new WC_Retailcrm_WC_Customer_Builder();
$builder
if (isset($customer['id'])) {
$this->customers->updateCustomerById($customer_id, $customer['id']);
$builder = new WC_Retailcrm_WC_Customer_Builder();
$builder
->setWcCustomer($wcCustomer)
->setPhones(isset($customer['phones']) ? $customer['phones'] : array())
->setAddress(isset($customer['address']) ? $customer['address'] : false)
@ -329,7 +315,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
->getResult()
->save();
}
} else {
} else {
$this->customers->createCustomer($customer_id);
}
}
@ -434,7 +420,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
*/
public function include_whatsapp_icon_style()
{
wp_register_style('whatsapp_icon_style', plugins_url() . '/woo-retailcrm/assets/css/whatsapp_icon.min.css', false, '0.1');
wp_register_style('whatsapp_icon_style', plugins_url() . '/woo-retailcrm/assets/css/whatsapp-icon.min.css', false, '0.1');
wp_enqueue_style('whatsapp_icon_style');
}
@ -458,6 +444,22 @@ if (!class_exists('WC_Retailcrm_Base')) {
}
/**
* Rerurn count upload data
*/
public function count_upload_data()
{
echo json_encode(
array(
'count_orders' => $this->uploader->getCountOrders(),
'count_users' => $this->uploader->getCountUsers()
)
);
wp_die();
}
/**
* Get retailcrm api client
*

View File

@ -90,42 +90,6 @@ if (!class_exists('WC_Retailcrm_Customers')) :
return $this->retailcrm->getCorporateEnabled();
}
/**
* Upload customers to CRM
*
* @param array $ids
*
* @return array mixed
*/
public function customersUpload($ids = array())
{
if (!$this->retailcrm) {
return null;
}
$users = get_users(array('include' => $ids));
$data_customers = array();
foreach ($users as $user) {
if (!$this->isCustomer($user)) {
continue;
}
$customer = $this->wcCustomerGet($user->ID);
$this->processCustomer($customer);
$data_customers[] = $this->customer;
}
$data = \array_chunk($data_customers, 50);
foreach ($data as $array_customers) {
$this->retailcrm->customersUpload($array_customers);
time_nanosleep(0, 250000000);
}
return $data;
}
/**
* Create customer in CRM
*
@ -335,6 +299,19 @@ if (!class_exists('WC_Retailcrm_Customers')) :
return $customerId;
}
/**
* Process customer for upload
*
* @param WC_Customer $customer
*
* @return void
*/
public function processCustomerForUpload($customer)
{
$this->processCustomer($customer);
}
/**
* Process customer
*

View File

@ -62,56 +62,6 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$this->order_payment = $order_payment;
}
/**
* Upload orders to CRM
*
* @param array $include
*
* @return array $uploadOrders | null
* @throws \Exception
*/
public function ordersUpload($include = array())
{
if (!$this->retailcrm) {
return null;
}
$uploader = new WC_Retailcrm_Customers(
$this->retailcrm,
$this->retailcrm_settings,
new WC_Retailcrm_Customer_Address()
);
$orders = get_posts(array(
'numberposts' => -1,
'post_type' => wc_get_order_types('view-orders'),
'post_status' => array_keys(wc_get_order_statuses()),
'include' => $include
));
$regularUploadErrors = array();
$corporateUploadErrors = array();
foreach ($orders as $data_order) {
$order = wc_get_order($data_order->ID);
$errorMessage = $this->orderCreate($data_order->ID);
if (is_string($errorMessage)) {
if ($this->retailcrm->getCorporateEnabled() && self::isCorporateOrder($order)) {
$corporateUploadErrors[$data_order->ID] = $errorMessage;
} else {
$regularUploadErrors[$data_order->ID] = $errorMessage;
}
}
}
static::logOrdersUploadErrors($regularUploadErrors, 'Error while uploading these regular orders');
static::logOrdersUploadErrors($corporateUploadErrors, 'Error while uploading these corporate orders');
return array();
}
/**
* Create order. Returns wc_get_order data or error string.
*
@ -599,27 +549,5 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
return $customerWasChanged;
}
/**
* Logs orders upload errors with prefix log message.
* Array keys must be orders ID's in WooCommerce, values must be strings (error messages).
*
* @param array $errors
* @param string $prefix
*/
public static function logOrdersUploadErrors($errors, $prefix = 'Errors while uploading these orders')
{
if (empty($errors)) {
return;
}
WC_Retailcrm_Logger::add($prefix);
foreach ($errors as $orderId => $error) {
WC_Retailcrm_Logger::add(sprintf("[%d] => %s", $orderId, $error));
}
WC_Retailcrm_Logger::add('==================================');
}
}
endif;
endif;

View File

@ -0,0 +1,236 @@
<?php
/**
* RetailCRM Integration.
*
* @package WC_Retailcrm_Uploader
* @category Integration
* @author RetailCRM
*/
if (class_exists('WC_Retailcrm_Uploader') === false) {
/**
* Class WC_Retailcrm_Uploader
*/
class WC_Retailcrm_Uploader
{
const RETAILCRM_COUNT_OBJECT_UPLOAD = 50;
/**
* Api client RetailCRM
*
* @var WC_Retailcrm_Client_V5
*/
private $retailcrm;
/**
* Orders RetailCRM
*
* @var WC_Retailcrm_Orders
*/
private $orders;
/**
* Customers RetailCRM
*
* @var WC_Retailcrm_Customers
*/
private $customers;
/**
* WC_Retailcrm_Uploader constructor.
*
* @param WC_Retailcrm_Client_V5 $retailcrm Api client RetailCRM.
* @param WC_Retailcrm_Orders $orders Object order RetailCRM.
* @param WC_Retailcrm_Customers $customers Object customer RetailCRM.
*/
public function __construct($retailcrm, $orders, $customers)
{
$this->retailcrm = $retailcrm;
$this->orders = $orders;
$this->customers = $customers;
}
/**
* Uploads selected order in CRM
*
* @return void
* @throws Exception Invalid argument exception.
*/
public function uploadSelectedOrders()
{
$response = filter_input(INPUT_GET, 'order_ids_retailcrm');
if (empty($response) === false) {
$ids = array_unique(explode(',', $response));
if (empty($ids) === false) {
$this->uploadArchiveOrders(0, $ids);
}
}
}
/**
* Uploads archive order in CRM
*
* @param integer $page Number page uploads.
* @param array $ids Ids orders upload.
*
* @return array
* @throws Exception Invalid argument exception.
*/
public function uploadArchiveOrders($page, $ids = array())
{
if (is_object($this->retailcrm) === false) {
return;
}
$uploadErrors = array();
$ordersCms = $this->getCmsOrders($page, $ids);
foreach ($ordersCms as $dataOrder) {
$orderId = $dataOrder->ID;
$errorMessage = $this->orders->orderCreate($orderId);
if (is_string($errorMessage) === true) {
$errorMessage = empty($errorMessage) === true ? 'Order exist. External id: ' . $orderId : $errorMessage;
$uploadErrors[$orderId] = $errorMessage;
}
}
$this->logOrdersUploadErrors($uploadErrors);
return array();
}
/**
* Uploads archive customer in CRM
*
* @param integer $page Number page uploads.
*
* @return array
* @throws Exception Invalid argument exception.
*/
public function uploadArchiveCustomers($page)
{
if (is_object($this->retailcrm) === false) {
return;
}
$users = $this->getCmsUsers($page);
if (empty($users) === false) {
$dataCustomers = array();
foreach ($users as $user) {
if ($this->customers->isCustomer($user) === false) {
continue;
}
$customer = new WC_Customer($user->ID);
$this->customers->processCustomerForUpload($customer);
$dataCustomers[] = $this->customers->getCustomer();
}
$this->retailcrm->customersUpload($dataCustomers);
}
return $dataCustomers;
}
/**
* Return orders ids
*
* @param integer $page Number page uploads.
* @param array $ids Ids orders upload.
*
* @return mixed
*/
private function getCmsOrders($page, $ids = array())
{
return get_posts(
array(
'numberposts' => self::RETAILCRM_COUNT_OBJECT_UPLOAD,
'offset' => self::RETAILCRM_COUNT_OBJECT_UPLOAD * $page,
'post_type' => wc_get_order_types('view-orders'),
'post_status' => array_keys(wc_get_order_statuses()),
'include' => $ids,
)
);
}
/**
* Return count orders
*
* @return integer
*/
public function getCountOrders()
{
global $wpdb;
$result = $wpdb->get_results("SELECT COUNT(ID) as `count` FROM $wpdb->posts WHERE post_type = 'shop_order'");
return empty($result[0]->count) === false ? $result[0]->count : 0;
}
/**
* Return users ids
*
* @param integer $page Number page uploads.
*
* @return mixed
*/
private function getCmsUsers($page)
{
return get_users(
array(
'number' => self::RETAILCRM_COUNT_OBJECT_UPLOAD,
'offset' => self::RETAILCRM_COUNT_OBJECT_UPLOAD * $page,
)
);
}
/**
* Return count users
*
* @return integer
*/
public function getCountUsers()
{
$userCount = count_users();
return empty($userCount['total_users']) === false ? $userCount['total_users'] : 0;
}
/**
* Array keys must be orders ID's in WooCommerce, values must be strings (error messages).
*
* @param array $errors Id order - key and message error - value.
*
* @return void
*/
private function logOrdersUploadErrors($errors)
{
if (empty($errors) === true) {
return;
}
WC_Retailcrm_Logger::add('Errors while uploading these orders');
foreach ($errors as $orderId => $error) {
WC_Retailcrm_Logger::add(sprintf("[%d] => %s", $orderId, $error));
}
WC_Retailcrm_Logger::add('==================================');
}
}
}//end if

Binary file not shown.

Binary file not shown.

View File

@ -122,7 +122,9 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
require_once(self::checkCustomFile('include/class-wc-retailcrm-ga.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-daemon-collector.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-base.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-uploader.php'));
require_once(self::checkCustomFile('include/functions.php'));
}
/**

View File

@ -19,11 +19,9 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
->disableOriginalConstructor()
->setMethods(array(
'ordersGet',
'ordersUpload',
'ordersCreate',
'ordersEdit',
'customersGet',
'customersUpload',
'customersCreate',
'customersEdit'
))
@ -59,23 +57,6 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertEquals($wc_customer, $retailcrm_customer->wcCustomerGet($this->customer->get_id()));
}
/**
* @param retailcrm
* @dataProvider dataProviderApiClient
*/
public function test_customers_upload($retailcrm)
{
$retailcrm_customer = $this->getRetailcrmCustomer($retailcrm);
$data = $retailcrm_customer->customersUpload();
if ($retailcrm) {
$this->assertInternalType('array', $data);
$this->assertInternalType('array', $data[0]);
$this->assertArrayHasKey('externalId', $data[0][0]);
} else {
$this->assertEquals(null, $data);
}
}
/**
* @param $retailcrm

View File

@ -12,7 +12,6 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
->disableOriginalConstructor()
->setMethods(array(
'ordersGet',
'ordersUpload',
'ordersCreate',
'ordersEdit',
'customersGet',
@ -26,22 +25,6 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
parent::setUp();
}
/**
* @param $retailcrm
* @dataProvider dataProviderRetailcrm
*/
public function test_order_upload($retailcrm)
{
$this->options = $this->setOptions();
$retailcrm_orders = $this->getRetailcrmOrders($retailcrm);
$upload_orders = $retailcrm_orders->ordersUpload();
if ($retailcrm) {
$this->assertInternalType('array', $upload_orders);
} else {
$this->assertEquals(null, $upload_orders);
}
}
/**
* @param $retailcrm

View File

@ -0,0 +1,145 @@
<?php
class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $apiMock;
protected $responseMock;
protected $customer;
public function setUp()
{
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response')
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor()
->setMethods(array(
'customersUpload',
'customersCreate',
'uploadArchiveCustomers',
'uploadArchiveOrders',
'getCountUsers',
'getCountOrders'
))
->getMock();
$this->responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$this->apiMock->expects($this->any())
->method('customersCreate')
->willReturn($this->responseMock);
$this->customer = new WC_Customer();
$this->customer->set_first_name('Tester');
$this->customer->set_last_name('Tester');
$this->customer->set_email(uniqid(md5(date('Y-m-d H:i:s'))) . '@mail.com');
$this->customer->set_billing_email($this->customer->get_email());
$this->customer->set_password('password');
$this->customer->set_billing_phone('89000000000');
$this->customer->set_date_created(date('Y-m-d H:i:s'));
$this->customer->save();
}
/**
* @param retailcrm
* @dataProvider dataProviderApiClient
*/
public function test_customers_upload($retailcrm)
{
$retailcrm_uploader = $this->getRetailcrmUploader($retailcrm);
$data = $retailcrm_uploader->uploadArchiveCustomers(0);
if ($retailcrm) {
$this->assertInternalType('array', $data);
$this->assertInternalType('array', $data[0]);
$this->assertArrayHasKey('externalId', $data[0]);
} else {
$this->assertEquals(null, $data);
}
}
/**
* @param $retailcrm
* @dataProvider dataProviderApiClient
*/
public function test_order_upload($retailcrm)
{
$retailcrm_uploader = $this->getRetailcrmUploader($retailcrm);
$data = $retailcrm_uploader->uploadArchiveOrders(0);
if ($retailcrm) {
$this->assertInternalType('array', $data);
} else {
$this->assertEquals(null, $data);
}
}
/**
* @param retailcrm
* @dataProvider dataProviderApiClient
*/
public function test_get_count_orders_upload($retailcrm)
{
$retailcrm_uploader = $this->getRetailcrmUploader($retailcrm);
$data = $retailcrm_uploader->getCountOrders();
if ($retailcrm) {
$this->assertInternalType('int', $data);
} else {
$this->assertEquals(null, $data);
}
}
public function dataProviderApiClient()
{
$this->setUp();
return array(
array(
'retailcrm' => $this->apiMock
),
array(
'retailcrm' => false
)
);
}
/**
* @param $retailcrm
*
* @return WC_Retailcrm_Customers
*/
private function getRetailcrmUploader($retailcrm)
{
$customer = new WC_Retailcrm_Customers(
$retailcrm,
$this->getOptions(),
new WC_Retailcrm_Customer_Address()
);
$order = new WC_Retailcrm_Orders(
$retailcrm,
$this->getOptions(),
new WC_Retailcrm_Order_Item($this->getOptions()),
new WC_Retailcrm_Order_Address,
new WC_Retailcrm_Customers(
$retailcrm, $this->getOptions(), new WC_Retailcrm_Customer_Address
),
new WC_Retailcrm_Order($this->getOptions()),
new WC_Retailcrm_Order_Payment($this->getOptions())
);
return new WC_Retailcrm_Uploader($retailcrm, $order, $customer);
}
}