1
0
mirror of synced 2025-01-31 07:11:42 +03:00
This commit is contained in:
Akolzin Dmitry 2018-05-28 12:56:19 +03:00
parent 1b8328b941
commit 01d970af8f
14 changed files with 231 additions and 93 deletions

View File

@ -1,3 +1,7 @@
## 2018-05-28 v3.1.0
* В интерфейс настроек плагина добавлена возможность ручной выгрузки заказов
* Исправлена инициализация кода UA для отправки заказов на всех страницах
## 2018-04-26 v3.0.0
* Добавлены тесты
* Произведен рефакторинг кода

View File

@ -1 +1 @@
3.0.0
3.1.0

View File

@ -60,8 +60,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('init', array($this, 'register_retailcrm_history'));
add_action('wp_ajax_do_upload', array($this, 'upload_to_crm'));
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);
add_action('woocommerce_update_customer', array($this, 'update_customer'), 10, 1);
add_action('woocommerce_update_order', array($this, 'update_order'), 11, 1);
@ -172,6 +174,27 @@ if (!class_exists('WC_Retailcrm_Base')) {
}
}
/**
* Upload selected orders
*/
public function order_upload() {
if (!class_exists('WC_Retailcrm_Orders')) {
include_once(self::checkCustomFile('orders'));
}
$ids = false;
if (isset($_GET['order_ids_retailcrm'])) {
$ids = explode(',', $_GET['order_ids_retailcrm']);
}
$retailcm_order = new WC_Retailcrm_Orders($this->apiClient);
if ($ids) {
$retailcm_order->ordersUpload($ids, true);
}
}
/**
* Upload archive customers and order to retailCRM
*/
@ -193,13 +216,13 @@ if (!class_exists('WC_Retailcrm_Base')) {
$retailcrm_orders->ordersUpload();
$options['uploads'] = 'yes';
update_option('woocommerce_integration-retailcrm_settings', $options);
update_option(self::$option_key, $options);
}
public function ajax_upload() {
$ajax_url = admin_url('admin-ajax.php');
?>
<script type="text/javascript" >
<script type="text/javascript">
jQuery('#uploads-retailcrm').bind('click', function() {
jQuery.ajax({
type: "POST",
@ -217,7 +240,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
public function ajax_generate_icml() {
$ajax_url = admin_url('admin-ajax.php');
?>
<script type="text/javascript" >
<script type="text/javascript">
jQuery('#icml-retailcrm').bind('click', function() {
jQuery.ajax({
type: "POST",
@ -232,6 +255,28 @@ if (!class_exists('WC_Retailcrm_Base')) {
<?php
}
public function ajax_selected_order() {
$ajax_url = admin_url('admin-ajax.php');
$ids = $this->plugin_id . $this->id . '_single_order';
?>
<script type="text/javascript">
jQuery('#single_order_btn').bind('click', function() {
if (jQuery('#<?php echo $ids; ?>').val() == '') {
alert('<?php echo __('Enter orders numbers', 'retailcrm'); ?>');
} else {
jQuery.ajax({
type: "POST",
url: '<?php echo $ajax_url; ?>?action=order_upload&order_ids_retailcrm=' + jQuery('#<?php echo $ids; ?>').val(),
success: function (response) {
alert('<?php echo __('Orders were unloaded', 'retailcrm'); ?>');
}
});
}
});
</script>
<?php
}
/**
* Create customer in retailCRM
* @param int $customer_id
@ -295,7 +340,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
include_once(self::checkCustomFile('ga'));
}
if ($this->get_option('ua') && $this->get_option('ua_code')) {
if ($this->get_option('ua') && $this->get_option('ua_code') && is_checkout()) {
$retailcrm_analytics = WC_Retailcrm_Google_Analytics::getInstance($this->settings);
echo $retailcrm_analytics->send_analytics();
} else {
@ -598,6 +643,33 @@ if (!class_exists('WC_Retailcrm_Base')) {
'desc_tip' => true,
'id' => 'icml-retailcrm'
);
/*
* Upload single order
*/
$this->form_field[] = array(
'title' => __( 'Upload single order by id', 'retailcrm' ),
'type' => 'title',
'description' => '',
'id' => 'order_options'
);
$this->form_fields['single_order'] = array(
'label' => __('Order ID', 'retailcrm'),
'title' => __('Enter id order', 'retailcrm'),
'type' => 'input',
'description' => __('Enter comma-separated order numbers.', 'retailcrm'),
'desc_tip' => true
);
$this->form_fields[] = array(
'label' => __('Upload', 'retailcrm'),
'title' => __('Upload single order by identificator', 'retailcrm'),
'type' => 'button',
'description' => __('This functionality allows you to upload single order to CRM.', 'retailcrm'),
'desc_tip' => true,
'id' => 'single_order_btn'
);
}
}
}

View File

@ -35,15 +35,16 @@ if (!class_exists('WC_Retailcrm_Customers')) :
/**
* Upload customers to CRM
*
* @return array $data
* @param array $ids
* @return array mixed
*/
public function customersUpload()
public function customersUpload($ids = array())
{
if (!$this->retailcrm) {
return;
return null;
}
$users = get_users();
$users = get_users(array('include' => $ids));
$data_customers = array();
foreach ($users as $user) {

View File

@ -59,9 +59,18 @@ if (!class_exists('WC_Retailcrm_Google_Analytics')) {
*/
public function send_analytics() {
$js = '';
if (!isset($_GET['key'])) {
return $js;
}
$order_id = wc_get_order_id_by_order_key($_GET['key']);
$order = wc_get_order($order_id);
if (!$order) {
return $js;
}
foreach ($order->get_items() as $item) {
$uid = ($item['variation_id'] > 0) ? $item['variation_id'] : $item['product_id'];
$_product = wc_get_product($uid);

View File

@ -192,7 +192,10 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$this->orderEdit($record, $options);
} catch (Exception $exception) {
$logger = new WC_Logger();
$logger->add('retailcrm', sprintf("[%s] - %s", $exception->getMessage(), 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()));
$logger->add('retailcrm',
sprintf("[%s] - %s", $exception->getMessage(),
'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine())
);
continue;
}
@ -214,52 +217,26 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
* @return void
*/
protected function removeFuncsHook()
{
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
remove_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
remove_action('woocommerce_saved_order_items', 'retailcrm_update_order_items', 10, 2);
remove_action('update_post_meta', 'retailcrm_update_order', 11, 4);
remove_action('woocommerce_payment_complete', 'retailcrm_update_order_payment', 11, 1);
remove_action('woocommerce_checkout_update_user_meta', 'update_customer', 10, 2);
} else {
remove_action('woocommerce_update_order', 'update_order', 11, 1);
remove_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
{
remove_action('woocommerce_update_order', 'update_order', 11, 1);
remove_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
/**
* Add function hooks after downloading history changes
*
*
* @return void
*/
protected function addFuncsHook()
{
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
if (!has_action('woocommerce_checkout_update_user_meta', 'update_customer')) {
add_action('woocommerce_checkout_update_user_meta', 'update_customer', 10, 2);
}
if (!has_action('woocommerce_order_status_changed', 'retailcrm_update_order_status')) {
add_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
if (!has_action('woocommerce_saved_order_items', 'retailcrm_update_order_items')) {
add_action('woocommerce_saved_order_items', 'retailcrm_update_order_items', 10, 2);
}
if (!has_action('update_post_meta', 'retailcrm_update_order')) {
add_action('update_post_meta', 'retailcrm_update_order', 11, 4);
}
if (!has_action('woocommerce_payment_complete', 'retailcrm_update_order_payment')) {
add_action('woocommerce_payment_complete', 'retailcrm_update_order_payment', 11, 1);
}
} else {
if (!has_action('woocommerce_update_order', 'update_order')) {
add_action('woocommerce_update_order', 'update_order', 11, 1);
}
if (!has_action('woocommerce_checkout_update_user_meta', 'update_customer')) {
add_action('woocommerce_checkout_update_user_meta', 'update_customer', 10, 2);
}
if (!has_action('woocommerce_order_status_changed', 'retailcrm_update_order_status')) {
add_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
{
if (!has_action('woocommerce_update_order', 'update_order')) {
add_action('woocommerce_update_order', 'update_order', 11, 1);
}
if (!has_action('woocommerce_checkout_update_user_meta', 'update_customer')) {
add_action('woocommerce_checkout_update_user_meta', 'update_customer', 10, 2);
}
if (!has_action('woocommerce_order_status_changed', 'retailcrm_update_order_status')) {
add_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
}
@ -268,7 +245,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
*
* @param array $record
* @param array $options
* @return void
* @return mixed
*/
protected function orderEdit($record, $options)
{
@ -345,7 +322,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$shipping_method = $shipping_methods[$method_id]['shipping_methods'][$options[$newValue]];
}
if ( is_object($crmOrder)) {
if (is_object($crmOrder)) {
if ($crmOrder->isSuccessful()) {
$deliveryCost = isset($crmOrder['order']['delivery']['cost']) ? $crmOrder['order']['delivery']['cost'] : 0;
}
@ -354,10 +331,15 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$args = array(
'method_id' => $options[$newValue],
'method_title' => isset($shipping_method) ? $shipping_method['title'] : $shipping_methods[$options[$newValue]]['name'],
'total' => $deliveryCost
'total' => isset($deliveryCost) ? $deliveryCost : 0
);
$item = $order->get_item((int)$item_id);
if (!$item) {
return false;
}
$item->set_order_id((int)$order->get_id());
$item->set_props($args);
$item->save();
@ -442,7 +424,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
&& isset($record['order']['orderMethod'])
&& !in_array($record['order']['orderMethod'], $this->order_methods)
) {
return;
return false;
}
$args = array(
@ -551,20 +533,15 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
}
}
if (version_compare(get_option('woocommerce_db_version'), '3.0', '<' )) {
$shipping_rate = new WC_Shipping_Rate($shipping_method_id, isset($shipping_method_title) ? $shipping_method_title : '', isset($shipping_total) ? floatval($shipping_total) : 0, array(), $shipping_method_id);
$order->add_shipping($shipping_rate);
} else {
$shipping = new WC_Order_Item_Shipping();
$shipping->set_props( array(
'method_title' => $shipping_method_title,
'method_id' => $shipping_method_id,
'total' => wc_format_decimal($shipping_total),
'order_id' => $order->get_id()
) );
$shipping->save();
$order->add_item( $shipping );
}
$shipping = new WC_Order_Item_Shipping();
$shipping->set_props( array(
'method_title' => $shipping_method_title,
'method_id' => $shipping_method_id,
'total' => wc_format_decimal($shipping_total),
'order_id' => $order->get_id()
) );
$shipping->save();
$order->add_item($shipping);
}
}
@ -599,9 +576,9 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
/**
* Calculate totals in order
*
* @param type $order
*
*
* @param WC_Order $order
*
* @return void
*/
protected function update_total($order)

View File

@ -29,9 +29,11 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
/**
* Upload orders to CRM
*
* @param bool $withCustomers
* @param array $include
* @return array $uploadOrders | null
*/
public function ordersUpload()
public function ordersUpload($include = array(), $withCustomers = false)
{
if (!$this->retailcrm) {
return null;
@ -40,7 +42,8 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$orders = get_posts(array(
'numberposts' => -1,
'post_type' => wc_get_order_types('view-orders'),
'post_status' => array_keys(wc_get_order_statuses())
'post_status' => array_keys(wc_get_order_statuses()),
'include' => $include
));
$orders_data = array();
@ -49,18 +52,33 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$order = wc_get_order($data_order->ID);
$this->processOrder($order);
$customer = $order->get_user();
$customers = array();
if ($customer != false) {
$this->order['customer']['externalId'] = $customer->get('ID');
if ($withCustomers === true) {
$customers[] = $customer->get('ID');
}
}
$orders_data[] = $this->order;
}
if ($withCustomers === true && !empty($customers)) {
if (!class_exists('WC_Retailcrm_Customers')) {
include_once(WC_Retailcrm_Base::checkCustomFile('customers'));
}
$retailcrmCustomer = new WC_Retailcrm_Customers($this->retailcrm);
$retailcrmCustomer->customersUpload($customers);
}
$uploadOrders = array_chunk($orders_data, 50);
foreach ($uploadOrders as $uploadOrder) {
$this->retailcrm->ordersUpload($uploadOrder);
time_nanosleep(0, 250000000);
}
return $uploadOrders;
@ -71,7 +89,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
*
* @param $order_id
*
* @return WC_Order $order | null
* @return mixed
*/
public function orderCreate($order_id)
{

Binary file not shown.

View File

@ -45,6 +45,9 @@ API-ключ должен быть для отдельного магазина
2. В появившихся списках справочников настройте соответствие способов доставки и оплаты, а так же статусов заказов. Отметьте галочку "Выгружать остатки", если хотите выгружать остатки из Retailcrm в магазин (подробнее смотрите в описании).
== Changelog ==
= 3.1.0 =
* В интерфейс настроек плагина добавлена возможность ручной выгрузки заказов
* Исправлена инициализация кода UA для отправки заказов на всех страницах
= 3.0.0 =
* Произведен рефакторинг кода
@ -120,8 +123,11 @@ API-ключ должен быть для отдельного магазина
== Upgrade Notice ==
= 3.1.0 =
В интерфейс настроек плагина добавлена возможность ручной выгрузки заказов
= 3.0.0 =
* Произведен рефакторинг кода
Произведен рефакторинг кода
= 2.1.4 =
Исправлена ошибка при активированном модуле без настроек

View File

@ -1,13 +1,13 @@
<?php
/**
* Version: 3.0.0
* Version: 3.1.0
* WC requires at least: 3.0
* WC tested up to: 3.3
* Plugin Name: WooCommerce RetailCRM
* Plugin URI: https://wordpress.org/plugins/woo-retailcrm/
* Description: Integration plugin for WooCommerce & RetailCRM
* Author: RetailDriver LLC
* Author URI: http://retailcrm.ru/
* Author URI: http://retailcrm.pro/
* Text Domain: retailcrm
*/
@ -72,5 +72,5 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
$plugin->register_activation_hook();
$plugin->register_deactivation_hook();
add_action( 'plugins_loaded', array( 'WC_Integration_Retailcrm', 'get_instance' ), 0 );
add_action('plugins_loaded', array('WC_Integration_Retailcrm', 'get_instance'), 0);
endif;

View File

@ -2,12 +2,12 @@
class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
{
protected function setOptions($apiVesrion)
protected function setOptions($apiVersion = 'v5')
{
$options = array(
'api_url' => 'https://example.retailcrm.ru',
'api_key' => 'dhsHJGYdjkHHJKJSGjhasjhgajsgJGHsg',
'api_version' => $apiVesrion,
'api_version' => $apiVersion,
'p_draft' => 'no',
'p_pending' => 'no',
'p_private' => 'no',
@ -32,9 +32,9 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
'refunded' => 'status6',
'failed' => 'status7',
'sync' => 'no',
'ua' => 'no',
'ua_code' => '',
'ua_custom' => '',
'ua' => 'yes',
'ua_code' => 'UA-XXXXXXX-XX',
'ua_custom' => '1',
'upload-button' => ''
);

View File

@ -14,6 +14,7 @@ function _manually_load_plugin() {
require $plugin_dir . 'src/include/class-wc-retailcrm-orders.php';
require $plugin_dir . 'src/include/class-wc-retailcrm-customers.php';
require $plugin_dir . 'src/include/class-wc-retailcrm-inventories.php';
require $plugin_dir . 'src/include/class-wc-retailcrm-ga.php';
require $plugin_dir . 'src/retailcrm.php';
}

View File

@ -0,0 +1,61 @@
<?php
class WC_Retailcrm_Google_Analytics_Test extends WC_Retailcrm_Test_Case_Helper
{
private $ga;
private $options;
private $order;
private $orderKey;
public function setUp()
{
$this->order = WC_Helper_Order::create_order(0);
$this->orderKey = $this->order->get_order_key();
$this->setOptions();
$this->options = get_option(WC_Retailcrm_Base::$option_key);
$this->ga = WC_Retailcrm_Google_Analytics::getInstance($this->options);
}
public function test_initialize_analytics()
{
$js = $this->ga->initialize_analytics();
$this->assertContains($this->options['ua_code'], $js);
$this->assertContains($this->options['ua_custom'], $js);
}
/**
* @param $checkout
* @dataProvider dataProvider
*/
public function test_send_analytics($checkout)
{
if ($checkout) {
$_GET['key'] = $this->orderKey;
}
$js = $this->ga->send_analytics();
if ($checkout) {
$this->assertContains((string)$this->order->get_id(), $js);
$this->assertContains((string)$this->order->get_total(), $js);
$this->assertContains((string)$this->order->get_total_tax(), $js);
$this->assertContains((string)$this->order->get_shipping_total(), $js);
} else {
$this->assertEmpty($js);
}
}
public function dataProvider()
{
return array(
array(
'checkout' => false
),
array(
'checkout' => true
)
);
}
}

View File

@ -254,17 +254,6 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
private function createTestOrder()
{
$this->order = WC_Helper_Order::create_order(0);
// var_dump($this->order);
// $this->order = new WC_Order();
// $this->order->set_payment_method('bacs');
// $this->order->set_billing_first_name('testFirstName');
// $this->order->set_billing_last_name('testLastName');
// $this->order->set_billing_country('RU');
// $this->order->set_billing_address_1('testAddress1');
// $this->order->set_billing_city('testCity');
// $this->order->set_billing_postcode('111111');
// $this->order->set_billing_email('test@mail.com');
// $this->order->save();
}
private function getResponseData($externalId)