From 1866514483804354b5638cef4a526b03150f6bda Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 16 Jan 2019 15:33:26 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=20Daemon=20Collector?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- resources/bin/pot_compile.sh | 5 + resources/pot/retailcrm-es_ES.pot | 203 +++++++++++++++++ resources/pot/retailcrm-ru_RU.pot | 212 ++++++++++++++++++ src/include/class-wc-retailcrm-base.php | 46 +++- .../class-wc-retailcrm-daemon-collector.php | 106 +++++++++ src/include/class-wc-retailcrm-ga.php | 2 + src/languages/retailcrm-es_ES.mo | Bin 5215 -> 5655 bytes src/languages/retailcrm-ru_RU.mo | Bin 6537 -> 7000 bytes tests/phpunit/bootstrap.php | 1 + .../test-wc-retailcrm-daemon-collector.php | 30 +++ 10 files changed, 603 insertions(+), 2 deletions(-) create mode 100755 resources/bin/pot_compile.sh create mode 100644 resources/pot/retailcrm-es_ES.pot create mode 100644 resources/pot/retailcrm-ru_RU.pot create mode 100644 src/include/class-wc-retailcrm-daemon-collector.php create mode 100644 tests/phpunit/test-wc-retailcrm-daemon-collector.php diff --git a/resources/bin/pot_compile.sh b/resources/bin/pot_compile.sh new file mode 100755 index 0000000..db6e82f --- /dev/null +++ b/resources/bin/pot_compile.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +DIRECTORY=$(cd `dirname $0` && pwd) + +msgfmt $DIRECTORY/../pot/retailcrm-ru_RU.pot -o $DIRECTORY/../../src/languages/retailcrm-ru_RU.mo +msgfmt $DIRECTORY/../pot/retailcrm-es_ES.pot -o $DIRECTORY/../../src/languages/retailcrm-es_ES.mo \ No newline at end of file diff --git a/resources/pot/retailcrm-es_ES.pot b/resources/pot/retailcrm-es_ES.pot new file mode 100644 index 0000000..c99cb16 --- /dev/null +++ b/resources/pot/retailcrm-es_ES.pot @@ -0,0 +1,203 @@ +# Translation of Plugins - Woocommerce RetailCRM - Development (trunk) in Spanish +# This file is distributed under the same license as the Plugins - Woocommerce RetailCRM - Development (trunk) package. +msgid "" +msgstr "" +"PO-Revision-Date: 2018-06-06 08:53:26+0000\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" +"X-Generator: GlotPress/2.4.0-alpha\n" +"Language: es\n" +"Project-Id-Version: Plugins - Woocommerce RetailCRM - Development (trunk)\n" + +#. Author URI of the plugin/theme +msgid "https://retailcrm.pro/" +msgstr "https://retailcrm.pro/" + +#. Author of the plugin/theme +msgid "RetailDriver LLC" +msgstr "RetailDriver LLC" + +#. Description of the plugin/theme +msgid "Integration plugin for WooCommerce & retailCRM" +msgstr "El plugin de integración para WooCommerce & retailCRM" + +#. Plugin URI of the plugin/theme +msgid "https://wordpress.org/plugins/woo-retailcrm/" +msgstr "https://wordpress.org/plugins/woo-retailcrm/" + +#. Plugin Name of the plugin/theme +msgid "WooCommerce retailCRM" +msgstr "WooCommerce retailCRM" + +msgid "This functionality allows to upload orders to CRM differentially." +msgstr "Esta función permite la subida selectiva de los pedidos al retailCRM." + +msgid "Uploading orders by identifiers." +msgstr "Subida de los pedidos por identificadores." + +msgid "Enter orders identifiers separated by a comma." +msgstr "Introduce los identificadores de pedidos separados por coma." + +msgid "Orders identifiers" +msgstr "Los identificadores de pedidos" + +msgid "Order identifier" +msgstr "Los identif de pedido" + +msgid "Upload the order by ID" +msgstr "Subir el pedido por ID" + +msgid "Orders were uploaded" +msgstr "Los pedidos están subidos" + +msgid "The field cannot be empty, enter the order ID" +msgstr "El campo no puede estar vacío, introduce el identificador de pedido" + +msgid "Catalog was generated" +msgstr "El catálogo está generado" + +msgid "Customers and orders were uploaded" +msgstr "Los clientes y pedidos están subidos" + +msgid "Enter the correct API key" +msgstr "Introduce la llave API correcta" + +msgid "Enter the correct URL of CRM" +msgstr "Introduce el enlace del retailCRM correcto" + +msgid "The selected API version is unavailable" +msgstr "La versión de API elegida no está disponible" + +msgid "This functionality allows to generate ICML products catalog for uploading to retailCRM." +msgstr "Esta función permite generar los catálogos de pedidos ICML para subida al retailCRM." + +msgid "Generating ICML" +msgstr "Generando ICML" + +msgid "Generate now" +msgstr "Generar ahora" + +msgid "Generating ICML catalog" +msgstr "Generar catálogo ICML" + +msgid "Settings" +msgstr "Ajustes" + +msgid "Uploading the existing customers and orders to retailCRM" +msgstr "Subida de los clientes existentes y pedidos al retailCRM." + +msgid "Uploading all customers and orders" +msgstr "Subir todos los clientes y pedidos" + +msgid "Upload" +msgstr "Subir" + +msgid "Settings of uploading" +msgstr "Ajustes de subida" + +msgid "User parameter" +msgstr "El parámetro personalizado" + +msgid "UA tracking code" +msgstr "El código de seguimiento UA" + +msgid "Enable this setting for uploading data to UA" +msgstr "Activa esta opción para subir los datos al UA." + +msgid "UA" +msgstr "UA" + +msgid "Activate UA" +msgstr "Activar UA" + +msgid "UA settings" +msgstr "Ajustes de UA" + +msgid "Enable this setting if you would like to get information on leftover stocks from retailCRM to the website." +msgstr "Active esta opción si quiere recibir la información del stock de los productos desde retailCRM a la página web." + +msgid "Stock balance" +msgstr "El stock" + +msgid "Synchronization of the stock balance" +msgstr "Sincronizar el stock" + +msgid "Setting of the stock balance" +msgstr "Ajustes del stock" + +msgid "Statuses" +msgstr "Los estados" + +msgid "Payment types" +msgstr "Métodos de pago" + +msgid "Delivery types" +msgstr "Métodos de envío" + +msgid "Select order methods which will be uploaded from retailCRM to the website" +msgstr "Elige el método de formalización de los pedidos que se van a subir desde retailCRM a la página web" + +msgid "Order methods available for uploading from retailCRM" +msgstr "Los métodos de la formalización de los pedidos disponibles para subida desde retailCRM" + +msgid "Order methods" +msgstr "Los métodos de la formalización del pedido" + +msgid "Catalog settings" +msgstr "Ajustes del catálogo" + +msgid "Select API version" +msgstr "Selecciona la versión de API" + +msgid "API version" +msgstr "Versión de API" + +msgid "API settings" +msgstr "Ajustes de API" + +msgid "Enter your API key. You can find it in the administration section of retailCRM" +msgstr "Introduce la llave API. Puede encontrarla en apartado administrativo del retailCRM" + +msgid "Enter with your API URL (https://yourdomain.retailcrm.pro)." +msgstr "Introduce enlace de API (https://yourdomain.retailcrm.pro)." + +msgid "Integration with retailCRM management system." +msgstr "La integración con el sistema de gestión del retailCRM ." + +msgid "Every 15 minutes" +msgstr "Cada 15 minutos" + +msgid "Every 3 hours" +msgstr "Cada 3 horas" + +msgid "Every 5 minutes" +msgstr "Cada 5 minutos" + +msgid "API Key" +msgstr "La llave API" + +msgid "API of URL" +msgstr "El enlace API" + +msgid "Main settings" +msgstr "Los ajustes generales" + +msgid "retailCRM" +msgstr "retailCRM" + +msgid "Daemon Collector settings" +msgstr "Ajustes de Daemon Collector" + +msgid "Activate Daemon Collector" +msgstr "Activar Daemon Collector" + +msgid "Daemon Collector" +msgstr "Daemon Collector" + +msgid "Enable this setting for activate Daemon Collector on site" +msgstr "Active esta configuración para activar Daemon Collector en la página web" + +msgid "Site key" +msgstr "Clave de la página web" \ No newline at end of file diff --git a/resources/pot/retailcrm-ru_RU.pot b/resources/pot/retailcrm-ru_RU.pot new file mode 100644 index 0000000..3690109 --- /dev/null +++ b/resources/pot/retailcrm-ru_RU.pot @@ -0,0 +1,212 @@ +# Translation of Plugins - Woocommerce RetailCRM - Development (trunk) in Russian +# This file is distributed under the same license as the Plugins - Woocommerce RetailCRM - Development (trunk) package. +msgid "" +msgstr "" +"PO-Revision-Date: 2018-06-06 08:53:26+0000\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" +"X-Generator: GlotPress/2.4.0-alpha\n" +"Language: ru\n" +"Project-Id-Version: Plugins - Woocommerce RetailCRM - Development (trunk)\n" + +#. Author URI of the plugin/theme +msgid "https://retailcrm.pro/" +msgstr "https://retailcrm.ru/" + +#. Author of the plugin/theme +msgid "RetailDriver LLC" +msgstr "RetailDriver LLC" + +#. Description of the plugin/theme +msgid "Integration plugin for WooCommerce & retailCRM" +msgstr "Интеграционный плагин для WooCommerce & retailCRM" + +#. Plugin URI of the plugin/theme +msgid "https://wordpress.org/plugins/woo-retailcrm/" +msgstr "https://wordpress.org/plugins/woo-retailcrm/" + +#. Plugin Name of the plugin/theme +msgid "WooCommerce retailCRM" +msgstr "WooCommerce retailCRM" + +msgid "Activate history uploads" +msgstr "Активировать загрузку истории изменений" + +msgid "Upload data from retailCRM" +msgstr "Загрузка данных из retailCRM" + +msgid "Generating ICML catalog by wp-cron" +msgstr "Генерация ICML каталога товаров с помощью wp-cron" + +msgid "This functionality allows to upload orders to CRM differentially." +msgstr "Эта функция позволяет производить выборочную выгрузку заказов в retailCRM" + +msgid "Uploading orders by identifiers." +msgstr "Выгрузка заказов по идентификаторам" + +msgid "Enter orders identifiers separated by a comma." +msgstr "Введите идентификаторы заказов через запятую" + +msgid "Orders identifiers" +msgstr "Идентификаторы заказов" + +msgid "Order identifier" +msgstr "Идентификатор заказа" + +msgid "Upload the order by ID" +msgstr "Выгрузить заказ по идентификатору" + +msgid "Orders were uploaded" +msgstr "Заказы были выгружены" + +msgid "The field cannot be empty, enter the order ID" +msgstr "Поле не может быть пустым, введите идентификатор заказа" + +msgid "Catalog was generated" +msgstr "Каталог был сгенерирован" + +msgid "Customers and orders were uploaded" +msgstr "Клиенты и заказы были выгружены" + +msgid "Enter the correct API key" +msgstr "Введите корректный API ключ" + +msgid "Enter the correct URL of CRM" +msgstr "Введите корректный адрес retailCRM" + +msgid "The selected API version is unavailable" +msgstr "Выбранная версия API недоступна" + +msgid "This functionality allows to generate ICML products catalog for uploading to retailCRM." +msgstr "Эта функция позволяет сгенерировать ICML каталог товаров для выгрузки в retailCRM" + +msgid "Generating ICML" +msgstr "Генерация ICML" + +msgid "Generate now" +msgstr "Сгенерировать сейчас" + +msgid "Generating ICML catalog" +msgstr "Генерация ICML каталога" + +msgid "Settings" +msgstr "Настройки" + +msgid "Uploading the existing customers and orders to retailCRM" +msgstr "Выгрузка существующих клиентов и заказов в retailCRM" + +msgid "Uploading all customers and orders" +msgstr "Выгрузка всех клиентов и заказов" + +msgid "Upload" +msgstr "Выгрузить" + +msgid "Settings of uploading" +msgstr "Настройки выгрузки" + +msgid "User parameter" +msgstr "Пользовательский параметр" + +msgid "UA tracking code" +msgstr "Код отслеживания UA" + +msgid "Enable this setting for uploading data to UA" +msgstr "Активируйте эту настройку для выгрузки данных в UA" + +msgid "UA" +msgstr "UA" + +msgid "Activate UA" +msgstr "Активировать UA" + +msgid "UA settings" +msgstr "Настройки UA" + +msgid "Enable this setting if you would like to get information on leftover stocks from retailCRM to the website." +msgstr "Активируйте данную настройку, если хотите получать остатки по товарам из retailCRM на сайт." + +msgid "Stock balance" +msgstr "Остатки" + +msgid "Synchronization of the stock balance" +msgstr "Синхронизация остатков" + +msgid "Setting of the stock balance" +msgstr "Настройка управления остатками" + +msgid "Statuses" +msgstr "Статусы" + +msgid "Payment types" +msgstr "Способы оплаты" + +msgid "Delivery types" +msgstr "Способы доставки" + +msgid "Select order methods which will be uploaded from retailCRM to the website" +msgstr "Выберите способы оформления заказов, которые будут выгружаться из retailCRM на сайт" + +msgid "Order methods available for uploading from retailCRM" +msgstr "Способы оформления заказа, доступные для выгрузки из retailCRM" + +msgid "Order methods" +msgstr "Способы оформления заказа" + +msgid "Catalog settings" +msgstr "Настройки каталога" + +msgid "Select API version" +msgstr "Выберите версию API" + +msgid "API version" +msgstr "Версия API" + +msgid "API settings" +msgstr "Настройки API" + +msgid "Enter your API key. You can find it in the administration section of retailCRM" +msgstr "Введите API ключ. Вы можете найти его в административном разделе retailCRM." + +msgid "Enter API of URL (https://yourdomain.retailcrm.pro)." +msgstr "Введите API URL (https://yourdomain.retailcrm.ru)." + +msgid "Integration with retailCRM management system." +msgstr "Интеграция с системой управления retailCRM" + +msgid "Every 15 minutes" +msgstr "Каждые 15 минут" + +msgid "Every 3 hours" +msgstr "Каждые 3 часа" + +msgid "Every 5 minutes" +msgstr "Каждые 5 минут" + +msgid "API key" +msgstr "API ключ" + +msgid "API of URL" +msgstr "API URL" + +msgid "Main settings" +msgstr "Главные настройки" + +msgid "retailCRM" +msgstr "retailCRM" + +msgid "Daemon Collector settings" +msgstr "Настройка Daemon Collector" + +msgid "Activate Daemon Collector" +msgstr "Активировать Daemon Collector" + +msgid "Daemon Collector" +msgstr "Daemon Collector" + +msgid "Enable this setting for activate Daemon Collector on site" +msgstr "Активируйте эту настройку для активации Daemon Collector на сайте" + +msgid "Site key" +msgstr "Ключ сайта" \ No newline at end of file diff --git a/src/include/class-wc-retailcrm-base.php b/src/include/class-wc-retailcrm-base.php index a67c532..b02c1ae 100644 --- a/src/include/class-wc-retailcrm-base.php +++ b/src/include/class-wc-retailcrm-base.php @@ -65,6 +65,7 @@ if (!class_exists('WC_Retailcrm_Base')) { add_action('woocommerce_update_customer', array($this, 'update_customer'), 10, 1); add_action('woocommerce_update_order', array($this, 'update_order'), 11, 1); add_action('wp_print_scripts', array($this, 'initialize_analytics'), 98); + add_action('wp_print_scripts', array($this, 'initialize_daemon_collector'), 99); add_action('wp_print_footer_scripts', array($this, 'send_analytics'), 99); // Deactivate hook @@ -351,7 +352,7 @@ if (!class_exists('WC_Retailcrm_Base')) { include_once(self::checkCustomFile('ga')); } - if ($this->get_option('ua') && $this->get_option('ua_code') && is_checkout()) { + if ($this->get_option('ua') == 'yes' && $this->get_option('ua_code') && is_checkout()) { $retailcrm_analytics = WC_Retailcrm_Google_Analytics::getInstance($this->settings); echo $retailcrm_analytics->send_analytics(); } else { @@ -359,6 +360,23 @@ if (!class_exists('WC_Retailcrm_Base')) { } } + /** + * Daemon collector + */ + public function initialize_daemon_collector() + { + if (!class_exists('WC_Retailcrm_Daemon_Collector')) { + include_once(self::checkCustomFile('daemon-collector')); + } + + if ($this->get_option('daemon_collector') == 'yes' && $this->get_option('daemon_collector_key')) { + $retailcrm_daemon_collector = WC_Retailcrm_Daemon_Collector::getInstance($this->settings); + echo $retailcrm_daemon_collector->initialize_daemon_collector(); + } else { + echo ''; + } + } + /** * Initialize integration settings form fields. */ @@ -591,7 +609,7 @@ if (!class_exists('WC_Retailcrm_Base')) { 'title' => __('UA settings', 'retailcrm'), 'type' => 'heading', 'description' => '', - 'id' => 'invent_options' + 'id' => 'ua_options' ); $this->form_fields['ua'] = array( @@ -614,6 +632,30 @@ if (!class_exists('WC_Retailcrm_Base')) { 'type' => 'input' ); + /** + * Daemon collector settings + */ + $this->form_fields[] = array( + 'title' => __('Daemon Collector settings', 'retailcrm'), + 'type' => 'heading', + 'description' => '', + 'id' => 'invent_options' + ); + + $this->form_fields['daemon_collector'] = array( + 'label' => __('Activate Daemon Collector', 'retailcrm'), + 'title' => __('Daemon Collector', 'retailcrm'), + 'class' => 'checkbox', + 'type' => 'checkbox', + 'description' => __('Enable this setting for activate Daemon Collector on site', 'retailcrm') + ); + + $this->form_fields['daemon_collector_key'] = array( + 'title' => __('Site key', 'retailcrm'), + 'class' => 'input', + 'type' => 'input' + ); + /** * Uploads options */ diff --git a/src/include/class-wc-retailcrm-daemon-collector.php b/src/include/class-wc-retailcrm-daemon-collector.php new file mode 100644 index 0000000..f21db44 --- /dev/null +++ b/src/include/class-wc-retailcrm-daemon-collector.php @@ -0,0 +1,106 @@ +options = $options; + } + + /** + * @return string + */ + public function initialize_daemon_collector() { + if (!$this->code) { + $this->buildHeader() + ->buildParams() + ->buildFooter(); + } + + return $this->code; + } + + /** + * @return $this + */ + private function buildHeader() { + $header = << + (function(_,r,e,t,a,i,l){_['retailCRMObject']=a;_[a]=_[a]||function(){(_[a].q=_[a].q||[]).push(arguments)};_[a].l=1*new Date();l=r.getElementsByTagName(e)[0];i=r.createElement(e);i.async=!0;i.src=t;l.parentNode.insertBefore(i,l)})(window,document,'script','https://collector.retailcrm.pro/w.js','_rc'); + +EOF; + + $this->code .= $header; + + return $this; + } + + /** + * @return $this + */ + private function buildParams() { + $params = array(); + + if ( + function_exists('WC') + && WC()->customer !== null + && WC()->customer->get_id() > 0 + ) { + $params['customerId'] = WC()->customer->get_id(); + } + + $this->code .= apply_filters('retailcrm_daemon_collector', '') . sprintf( + "\t_rc('create', '%s', %s);\n", + $this->options['daemon_collector_key'], + json_encode((object) $params) + ); + + return $this; + } + + /** + * @return $this + */ + private function buildFooter() { + $footer = << + +EOF; + + $this->code .= $footer; + + return $this; + } +} diff --git a/src/include/class-wc-retailcrm-ga.php b/src/include/class-wc-retailcrm-ga.php index aef2030..fe2be39 100644 --- a/src/include/class-wc-retailcrm-ga.php +++ b/src/include/class-wc-retailcrm-ga.php @@ -7,6 +7,8 @@ if (!class_exists('WC_Retailcrm_Google_Analytics')) { private $options; /** + * @param array $options + * * @return WC_Retailcrm_Google_Analytics */ public static function getInstance($options = array()) diff --git a/src/languages/retailcrm-es_ES.mo b/src/languages/retailcrm-es_ES.mo index 19b8e1137ebb4a07a0ed64d0061cc7c19f64ed89..fa24d2750a84ca647dbbc3b667350e8608538444 100644 GIT binary patch delta 1797 zcmZY9Piz!r7{~F4(&b;f{U@S;(iha)ViyDvTScL?q8K#-u|SL_)7@z^Wt~}fXGWX&SE=$h;8^8Zp8VteHpuG zH}GEk6}RDyv_HG5IerUvnAL2En_&jLfP?rxPUE+@12^(^z2HSufD`x(*6>yQ9`(X? zYs|8^89Q+R73gr8r8o6v%KGWxp^3Kn8Ty^D4xONcpgVk`DSCmEA!F+}_=6Z$d3}0Qcend>T)8lYd2gi4J)c2XO&U zU>jj>!2)i=50JU-tJLrCLE1l{j|<47Hg-?*)QqFrZ=pWE5|VxU81)T&UgJg|)jW>j zCES6xa2)&i@esa;+WRZ0mHmkN$bLgkmfb|H@HT4iJ6Vk~wi|W2-b8K5S>(^^Tr|FR zjT^1_I%@B;^s@EIYMCpET6;@8NzsR-qE)LXh-aw^;&H0Vb5u>flA8V-N#@qd7mKpu zbpEx!I^PQ7DXNP0au0PURq58As`OJi?zWZMN7YLAQ&p5T6{S^Mwpg@kWkO{aRo{<_ z_J5zwzmCpB>Y)rYNv=AAi$$q_g1VdfWZJnG+3w^EPrH(1{1^?AnQW8#m41DsD!C@f zsj-pQ4!gO(TX%JhdH&l`=tiSr(a*8hn-My9Kk z*sr+4@^{)RjSF#9h>{=uaHjE1WFrdDcYY=ITs{gXgQ;rS%Lk2m=t^GMbIk>mm&fmi zuIRb8Qse8XAoSd6f1>_w_FPNH%S;~>{4fqCiDB+k*I<3R>x~uL?+&a|od^n^jTSv# PO`uG4_dGv$f7b2{c(~RCD9~;pqqk` z)lD}MUZfz*NP;A&Zo=TTyP)zy!=ft*y66w|{cY~S^M2m5`JQv0=bU%CNUX5k8E<6m5hndu1&a2@?pEWlbU!^4=1=g@~EcoxU8 z+L(y(IE~rJ2Q8=tbm4xyf^9gB8aS0zP_(xiFOpxTrs$nd5xG7^WB1A4Fvm!Fn9SMtqN2SO#TMNsG~k0X&66 zSd4SH34b7e#_3L2h(+|h7{q{^`g3n4xX4*9RLR(=J^h3_6JPNV{>Ex-q6{Z-00a0I z9hjY$NW_IYBSpwTH;t%-no(QXiK@^@gd4qjPf(>^KxOy`^?;k%m7y24mnV>|G<#{x z89!j!GCiwMRkUzruje&+6-|rQg!QyNwB0mCWNX6sB6O>htI$3wv`@Ss@zCp~bD$C` zl%ay30<(dpty9#|N@?T}4`r;R6g9McG_N{(|CJp{#k1Rm6*PtRt(K kaX&jhYT3{2DRpJ+vwJip%jyeSL&LrOeLb;Td3PQE0dHK9XaE2J diff --git a/src/languages/retailcrm-ru_RU.mo b/src/languages/retailcrm-ru_RU.mo index e443e55bd4ad0172bf1f2e4cbaea9c1108e71531..f8443906728df05edd44345ed2858ca057462fc4 100644 GIT binary patch delta 1738 zcmZY9X>5&I9LMp$>aC^PQfgmrQR}t#s;NO$D+nQ$SOzbOi)v}6y%|e0?i3kogx&~| zh%I7C$fdScNRTj@%uJq}zQGH;K_y;DL~bNA;rn~~Oh|ju)6Y52a+d%9Ja=F2)4a%w z%;cj+nNICX4J4T@$H~e3qn!4cwZk*m5iemUyn(6s0DIxzUjHrjr2i2+W2Y3eEbNB^ zF&A}x3G!aV*3(GmLJj8QVGQ7(xDgW=#MP`~G#*1u_!za|S2z#Hm=IOWn)k|pMjcZ0|u}f3ovq##$*~zScEym zYdMzUIDCW}=#ytE+tL8ps53DSITG$}b-J0~J&bxs<;P~+bgJ2(I*rQDgN@hsuTn^5 zBi5Gc{qDFwHacYg7ez%oQ5ac^dw?dPioTjWsus*qaKC%75mX&eMOJCiS2dlgqV&1* zYZrdCz2g1~(jG$1rB3y(PeFxDpH_}{O)1Iu+B)&ymkD%&)QQw2s?x=AanBF9rJq)% zZ=AHd`BsjU4jmemG0j-7=mcMW=i-vkri#t}qKfkJ(3)^XWpu6Y=ix1`S<8p~RiSXW zbo2VEXrpgfcFCG>=`SVWkiXSq3|v(j4n;Fkvg#7Pqix&K@t1|R)$Q+4nB02mYiWsK z%Q4J3>BQnS@tyJCocm6_)8NEf%@e(l{?quF(-7b3+;Oh+`0se9)nk6=9xumhoS0M3 cqc`iGq@PO3JmK7pAByk!c0E?NHY+FjD@4EZTmS$7 delta 1392 zcmZwHOGs2v9LMof&ZD&S`WjO+Ep6_8Q~I2xemoF2LQGgI%sMT*UEdv~UoM@ft3}BW-4jPq6Y0eQyn{vf$o>B%Y673!|EIB)WAFUTMB9*4<^*cxarbx#HQ^Dg z!CR<_JjGg`Z+_9~#0v7;f^nn@<~}OL4^R(&f+WMd!7`l00M4LRYH@KDhA@mBsFV+* zCUhNj{Wz)wX|#E^`Aw&14juBSRK}Su*)n~o8wODm7{ziN$6fdWtFeryD8)^<8Bby* z-o}IY3~yo$^@`wQ?7+WyT-ln5kA7aaLjp;_!vKRG$E2vuC#b$hm zQ7q+M+lB|Q3$NmO{D~STNV;Scb^m@;sclrHLxdJ$Z{lYIq1HfXgXIvapFROw2sOQG z%FHTaEm1|NvG<&sY7w(7OsA2kAT+7}HD!y5+0KV&_5#&Nt5b76M!1~dTj4Z6zsk-M zLaU)#PE(0kxbyl2GpC%@s|4&(=e1Uu*d9*(NrG8P1e8TGtiC-F7+L*jX{mGE1wsR=9QOEr{Kd;S4V CaeCDN diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php index 0cc1105..f531b62 100644 --- a/tests/phpunit/bootstrap.php +++ b/tests/phpunit/bootstrap.php @@ -15,6 +15,7 @@ function _manually_load_plugin() { 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/include/class-wc-retailcrm-daemon-collector.php'; require $plugin_dir . 'src/include/class-wc-retailcrm-history.php'; require $plugin_dir . 'src/retailcrm.php'; } diff --git a/tests/phpunit/test-wc-retailcrm-daemon-collector.php b/tests/phpunit/test-wc-retailcrm-daemon-collector.php new file mode 100644 index 0000000..ce33567 --- /dev/null +++ b/tests/phpunit/test-wc-retailcrm-daemon-collector.php @@ -0,0 +1,30 @@ +options = array( + 'daemon_collector_key' => 'RC-XXXXXXXXXX-X' + ); + + $this->daemonCollector = WC_Retailcrm_Daemon_Collector::getInstance($this->options); + } + + public function test_initialize_daemon_collector() + { + $customerObject = WC_Helper_Customer::create_customer(); + WC()->customer = $customerObject; + + $js = $this->daemonCollector->initialize_daemon_collector(); + + $this->assertContains('customerId', $js); + $this->assertContains($this->options['daemon_collector_key'], $js); + $this->assertContains('assertContains('', $js); + $this->assertContains('_rc(\'create\',', $js); + } +} From c110053075ccdccde9f35d5826029345733f6efa Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Thu, 17 Jan 2019 15:58:13 +0300 Subject: [PATCH 2/2] v3.4.0 --- CHANGELOG.md | 4 + VERSION | 2 +- src/include/class-wc-retailcrm-customers.php | 115 ++++++++++++++++-- src/include/class-wc-retailcrm-history.php | 10 +- src/include/class-wc-retailcrm-orders.php | 92 +++++++------- src/readme.txt | 7 ++ src/retailcrm.php | 2 +- src/uninstall.php | 2 +- tests/phpunit/test-wc-retailcrm-customers.php | 14 ++- tests/phpunit/test-wc-retailcrm-orders.php | 42 ++++++- 10 files changed, 229 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c36965..44b0c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2019-01-17 v3.4.0 +* Добавлена настройка Daemon Collector +* Изменена логика передачи данных по заказам и клиентам. Данные доставки передаются в заказ, данные оплаты в карточку клиента. + ## 2018-12-14 v3.3.8 * Добавлена выгрузка картинок для категорий товаров в ICML diff --git a/VERSION b/VERSION index 7cb75ca..fbcbf73 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.3.8 \ No newline at end of file +3.4.0 \ No newline at end of file diff --git a/src/include/class-wc-retailcrm-customers.php b/src/include/class-wc-retailcrm-customers.php index 5ad1ef4..90f6d12 100644 --- a/src/include/class-wc-retailcrm-customers.php +++ b/src/include/class-wc-retailcrm-customers.php @@ -68,26 +68,67 @@ if (!class_exists('WC_Retailcrm_Customers')) : } /** - * Create customer in CRM + * @param array $orders * - * @param int $customer_id - * - * @return WC_Customer $customer + * @throws Exception */ - public function createCustomer($customer_id) + public function customersFromOrdersUpload($orders) { - if (!$this->retailcrm) { - return; + $data_customers = array(); + + foreach ($orders as $order_data) { + $order = wc_get_order($order_data->ID); + + if ($order->get_user()) { + continue; + } + + $customer = $this->buildCustomerFromOrderData($order); + $this->processCustomer($customer); + $data_customers[] = $this->customer; } - $customer = $this->wcCustomerGet($customer_id); + if ($data_customers) { + $data = \array_chunk($data_customers, 50); + + foreach ($data as $array_customers) { + $this->retailcrm->customersUpload($array_customers); + time_nanosleep(0, 250000000); + } + } + } + + /** + * Create customer in CRM + * + * @param int | WC_Customer $customer + * + * @return mixed + */ + public function createCustomer($customer) + { + if (!$this->retailcrm) { + return null; + } + + if (is_int($customer)) { + $customer = $this->wcCustomerGet($customer); + } + + if (!$customer instanceof WC_Customer) { + return null; + } if ($customer->get_role() == self::CUSTOMER_ROLE) { $this->processCustomer($customer); - $this->retailcrm->customersCreate($this->customer); + $response = $this->retailcrm->customersCreate($this->customer); + + if ($response->isSuccessful() && isset($response['id'])) { + return $response['id']; + } } - return $customer; + return null; } /** @@ -126,7 +167,7 @@ if (!class_exists('WC_Retailcrm_Customers')) : $firstName = $customer->get_first_name(); $data_customer = array( 'createdAt' => $createdAt->date('Y-m-d H:i:s'), - 'externalId' => $customer->get_id(), + 'externalId' => $customer->get_id() > 0 ? $customer->get_id() : uniqid(), 'firstName' => $firstName ? $firstName : $customer->get_username(), 'lastName' => $customer->get_last_name(), 'email' => $customer->get_email(), @@ -148,6 +189,58 @@ if (!class_exists('WC_Retailcrm_Customers')) : $this->customer = apply_filters('retailcrm_process_customer', $data_customer, $customer); } + /** + * @param array $filter + * + * @return bool|array + */ + public function searchCustomer($filter) + { + if (isset($filter['id'])) { + $search = $this->retailcrm->customersGet($filter['id']); + } elseif (isset($filter['email'])) { + $search = $this->retailcrm->customersList(array('email' => $filter['email'])); + } + + if ($search->isSuccessful()) { + if (isset($search['customers'])) { + if (empty($search['customers'])) { + return false; + } + + $customer = reset($search['customers']); + } else { + $customer = $search['customer']; + } + + return $customer; + } + + return false; + } + + /** + * @param WC_Order $order + * + * @return WC_Customer + * @throws Exception + */ + public function buildCustomerFromOrderData($order) + { + $new_customer = new WC_Customer; + + foreach ($order->get_address('billing') as $prop => $value) { + $new_customer->{'set_billing_' . $prop}($value); + } + + $new_customer->set_first_name($order->get_billing_first_name()); + $new_customer->set_last_name($order->get_billing_last_name()); + $new_customer->set_email($order->get_billing_email()); + $new_customer->set_date_created($order->get_date_created()); + + return $new_customer; + } + /** * @param int $customer_id * diff --git a/src/include/class-wc-retailcrm-history.php b/src/include/class-wc-retailcrm-history.php index 164fe13..852704e 100644 --- a/src/include/class-wc-retailcrm-history.php +++ b/src/include/class-wc-retailcrm-history.php @@ -93,6 +93,14 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) : continue; } + if (isset($record['customer']['externalId'])) { + $customer = new WC_Customer($record['customer']['externalId']); + + if ($customer->get_id() == 0) { + continue; + } + } + WC_Retailcrm_Plugin::$history_run = true; if ($record['field'] == 'first_name' && isset($record['customer']['externalId'])) { @@ -102,7 +110,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) : } elseif ($record['field'] == 'last_name' && isset($record['customer']['externalId'])) { - if ($record['newValue']){ + if ($record['newValue']) { update_user_meta($record['customer']['externalId'], 'last_name', $record['newValue']); } } diff --git a/src/include/class-wc-retailcrm-orders.php b/src/include/class-wc-retailcrm-orders.php index 5b65e0c..5a08a24 100644 --- a/src/include/class-wc-retailcrm-orders.php +++ b/src/include/class-wc-retailcrm-orders.php @@ -65,12 +65,17 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) : $orders_data[] = $this->order; } - if ($withCustomers === true && !empty($customers)) { - if (!class_exists('WC_Retailcrm_Customers')) { - include_once(WC_Retailcrm_Base::checkCustomFile('customers')); - } + if (!class_exists('WC_Retailcrm_Customers')) { + include_once(WC_Retailcrm_Base::checkCustomFile('customers')); + } - $retailcrmCustomer = new WC_Retailcrm_Customers($this->retailcrm); + $retailcrmCustomer = new WC_Retailcrm_Customers($this->retailcrm); + + if (!$include) { + $retailcrmCustomer->customersFromOrdersUpload($orders); + } + + if ($withCustomers === true && !empty($customers)) { $retailcrmCustomer->customersUpload($customers); } @@ -101,21 +106,35 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) : $this->processOrder($order); $customer = $order->get_user(); + if (!class_exists('WC_Retailcrm_Customers')) { + include_once(WC_Retailcrm_Base::checkCustomFile('customers')); + } + + $retailcrm_customers = new WC_Retailcrm_Customers($this->retailcrm); + if ($customer != false) { - $search = $this->retailcrm->customersGet($customer->get('ID')); + $search = $retailcrm_customers->searchCustomer(array('id' => $customer->get('ID'))); - if (!$search->isSuccessful()) { - $customer_data = array( - 'externalId' => $customer->get('ID'), - 'firstName' => $this->order['firstName'], - 'lastName' => $this->order['lastName'], - 'email' => $this->order['email'] - ); - - $this->retailcrm->customersCreate($customer_data); + if (!$search) { + $retailcrm_customers->createCustomer($customer); } else { - $this->order['customer']['externalId'] = $search['customer']['externalId']; + $this->order['customer']['externalId'] = $search['externalId']; } + } else { + $search = $retailcrm_customers->searchCustomer(array('email' => $order->get_billing_email())); + + if (!$search) { + $new_customer = $retailcrm_customers->buildCustomerFromOrderData($order); + $id = $retailcrm_customers->createCustomer($new_customer); + + if ($id !== null) { + $this->order['customer']['id'] = $id; + } + } else { + $this->order['customer']['externalId'] = $search['externalId']; + } + + unset($new_customer); } $this->retailcrm->ordersCreate($this->order); @@ -294,36 +313,28 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) : $user_data_billing = $order->get_address('billing'); if (!empty($user_data_billing)) { - if (!empty($user_data_billing['phone'])) $order_data['phone'] = $user_data_billing['phone']; - if (!empty($user_data_billing['email'])) $order_data['email'] = $user_data_billing['email']; - if (!empty($user_data_billing['first_name'])) $order_data['firstName'] = $user_data_billing['first_name']; - if (!empty($user_data_billing['last_name'])) $order_data['lastName'] = $user_data_billing['last_name']; - if (!empty($user_data_billing['postcode'])) $order_data['delivery']['address']['index'] = $user_data_billing['postcode']; - if (!empty($user_data_billing['city'])) $order_data['delivery']['address']['city'] = $user_data_billing['city']; - if (!empty($user_data_billing['state'])) $order_data['delivery']['address']['region'] = $user_data_billing['state']; - if (!empty($user_data_billing['country'])) $order_data['countryIso'] = $user_data_billing['country']; + $order_data['phone'] = $user_data_billing['phone']; + $order_data['email'] = $user_data_billing['email']; } - $user_data = $order->get_address('shipping'); + $user_data_shipping = $order->get_address('shipping'); - if (!empty($user_data)) { - if (!empty($user_data['phone'])) $order_data['phone'] = $user_data['phone']; - if (!empty($user_data['email'])) $order_data['email'] = $user_data['email']; - if (!empty($user_data['first_name'])) $order_data['firstName'] = $user_data['first_name']; - if (!empty($user_data['last_name'])) $order_data['lastName'] = $user_data['last_name']; - if (!empty($user_data['postcode'])) $order_data['delivery']['address']['index'] = $user_data['postcode']; - if (!empty($user_data['city'])) $order_data['delivery']['address']['city'] = $user_data['city']; - if (!empty($user_data['state'])) $order_data['delivery']['address']['region'] = $user_data['state']; - if (!empty($user_data['country'])) $order_data['delivery']['address']['countryIso'] = $user_data['country']; + if (!empty($user_data_shipping)) { + $order_data['firstName'] = $user_data_shipping['first_name']; + $order_data['lastName'] = $user_data_shipping['last_name']; + $order_data['delivery']['address']['index'] = $user_data_shipping['postcode']; + $order_data['delivery']['address']['city'] = $user_data_shipping['city']; + $order_data['delivery']['address']['region'] = $user_data_shipping['state']; + $order_data['countryIso'] = $user_data_shipping['country']; } $order_data['delivery']['address']['text'] = sprintf( "%s %s %s %s %s", - !empty($user_data_billing['postcode']) ? $user_data_billing['postcode'] : $user_data['postcode'], - !empty($user_data_billing['state']) ? $user_data_billing['state'] : $user_data['state'], - !empty($user_data_billing['city']) ? $user_data_billing['city'] : $user_data['city'], - !empty($user_data_billing['address_1']) ? $user_data_billing['address_1'] : $user_data['address_1'], - !empty($user_data_billing['address_2']) ? $user_data_billing['address_2'] : $user_data['address_2'] + $user_data_shipping['postcode'], + $user_data_shipping['state'], + $user_data_shipping['city'], + $user_data_shipping['address_1'], + $user_data_shipping['address_2'] ); $order_items = array(); @@ -414,8 +425,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) : $payment['paidAt'] = trim($pay_date->date('Y-m-d H:i:s')); } - if ($update === false){ - + if ($update === false) { if (isset($this->retailcrm_settings[$order->get_payment_method()])) { $payment['type'] = $this->retailcrm_settings[$order->get_payment_method()]; } diff --git a/src/readme.txt b/src/readme.txt index 98a2ed3..f09edc0 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -45,6 +45,10 @@ API-ключ должен быть для отдельного магазина 2. В появившихся списках справочников настройте соответствие способов доставки и оплаты, а так же статусов заказов. Отметьте галочку "Выгружать остатки", если хотите выгружать остатки из Retailcrm в магазин (подробнее смотрите в описании). == Changelog == += 3.4.0 = +* Добавлена настройка Daemon Collector +* Изменена логика передачи данных по заказам и клиентам. Данные доставки передаются в заказ, данные оплаты в карточку клиента. + = 3.3.8 = * Добавлена выгрузка картинок для категорий товаров в ICML @@ -159,6 +163,9 @@ API-ключ должен быть для отдельного магазина * Исправелены ошибки. == Upgrade Notice == += 3.4.0 = +Внедрен Daemon Collector + = 3.3.5 = После обновления плагина необходимо пересохранить настройки для того, чтобы активировать модуль в маркетплейсе retailCRM diff --git a/src/retailcrm.php b/src/retailcrm.php index 65437d8..644c91a 100644 --- a/src/retailcrm.php +++ b/src/retailcrm.php @@ -1,6 +1,6 @@ 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_email(uniqid(md5(date('Y-m-d H:i:s'))) . '@mail.com'); $this->customer->set_password('password'); - $this->customer->set_role(WC_Retailcrm_Customers::CUSTOMER_ROLE); $this->customer->set_billing_phone('89000000000'); $this->customer->save(); } @@ -73,7 +80,7 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper public function test_create_customer($retailcrm) { $retailcrm_customer = new WC_Retailcrm_Customers($retailcrm); - $customer = $retailcrm_customer->createCustomer($this->customer->get_id()); + $id = $retailcrm_customer->createCustomer($this->customer->get_id()); $customer_send = $retailcrm_customer->getCustomer(); if ($retailcrm) { @@ -84,9 +91,8 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper $this->assertNotEmpty($customer_send['externalId']); $this->assertNotEmpty($customer_send['firstName']); $this->assertNotEmpty($customer_send['email']); - $this->assertInstanceOf('WC_Customer', $customer); } else { - $this->assertEquals(null, $customer); + $this->assertEquals(null, $id); $this->assertEquals(array(), $customer_send); } } diff --git a/tests/phpunit/test-wc-retailcrm-orders.php b/tests/phpunit/test-wc-retailcrm-orders.php index 5907045..0e8fe8a 100644 --- a/tests/phpunit/test-wc-retailcrm-orders.php +++ b/tests/phpunit/test-wc-retailcrm-orders.php @@ -18,7 +18,8 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper 'customersGet', 'customersCreate', 'ordersPaymentCreate', - 'ordersPaymentDelete' + 'ordersPaymentDelete', + 'customersList' )) ->getMock(); @@ -50,6 +51,36 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper */ public function test_order_create($retailcrm, $apiVersion) { + if ($retailcrm) { + $responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(array( + 'isSuccessful' + )) + ->getMock(); + + $responseMockCustomers = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') + ->disableOriginalConstructor() + ->setMethods(array( + 'isSuccessful' + )) + ->getMock(); + $responseMockCustomers->setResponse( + array('success' => true, + 'customers' => array( + array('externalId' => 1) + ) + ) + ); + + $retailcrm->expects($this->any()) + ->method('customersCreate') + ->willReturn($responseMock); + $retailcrm->expects($this->any()) + ->method('customersList') + ->willReturn($responseMockCustomers); + } + $this->createTestOrder(); $this->options = $this->setOptions($apiVersion); $retailcrm_orders = new WC_Retailcrm_Orders($retailcrm); @@ -252,7 +283,16 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper private function createTestOrder() { + /** @var WC_Order order */ $this->order = WC_Helper_Order::create_order(0); + + foreach ($this->order->get_address('billing') as $prop => $value) { + if (method_exists($this->order, 'set_shipping_' . $prop)) { + $this->order->{'set_shipping_' . $prop}($value); + } + } + + $this->order->save(); } private function getResponseData($externalId)