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

Update old tests, add new tests

This commit is contained in:
Dima Uryvskiy 2021-12-20 11:41:41 +03:00 committed by GitHub
parent b0577a18fb
commit 6132172da5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 4019 additions and 2805 deletions

View File

@ -464,6 +464,7 @@ jobs:
php --version php --version
composer --version composer --version
phpunit --version phpunit --version
- name: Install Woocommerce - name: Install Woocommerce
env: env:
WP_VERSION: ${{ matrix.wp }} WP_VERSION: ${{ matrix.wp }}

View File

@ -1,3 +1,10 @@
## 2021-12-15 4.4.0
* Migrating to PHP 5.6. We tested the module, improved performance, security and test coverage.
* Add validate countryIso. Fix bug with duplicate customer address
* Fix bugs in history
* Fix PHP warning and deprecated
* Add documentation for module
## 2021-08-30 4.3.8 ## 2021-08-30 4.3.8
* Updated logic work address * Updated logic work address
* Added transfer of the client's comment to the WC order * Added transfer of the client's comment to the WC order

View File

@ -1 +1 @@
4.3.8 4.4.0

View File

@ -21,6 +21,8 @@ abstract class WC_Retailcrm_Abstract_Builder implements WC_Retailcrm_Builder_Int
/** /**
* @return array|mixed * @return array|mixed
*
* @codeCoverageIgnore
*/ */
public function getData() public function getData()
{ {

View File

@ -29,6 +29,9 @@ abstract class WC_Retailcrm_Abstracts_Data
*/ */
abstract public function build($data); abstract public function build($data);
/**
* @codeCoverageIgnore
*/
protected function set_data_field($field, $value) protected function set_data_field($field, $value)
{ {
if (isset($this->data[$field]) && \gettype($value) !== \gettype($this->data[$field])) { if (isset($this->data[$field]) && \gettype($value) !== \gettype($this->data[$field])) {
@ -45,8 +48,10 @@ abstract class WC_Retailcrm_Abstracts_Data
*/ */
protected function set_data_fields($fields) protected function set_data_fields($fields)
{ {
foreach ($fields as $field => $value) { if (!empty($fields)) {
$this->set_data_field($field, $value); foreach ($fields as $field => $value) {
$this->set_data_field($field, $value);
}
} }
} }

View File

@ -39,6 +39,9 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
} }
/**
* @codeCoverageIgnore
*/
public function ajax_generate_icml() public function ajax_generate_icml()
{ {
$ajax_url = admin_url('admin-ajax.php'); $ajax_url = admin_url('admin-ajax.php');
@ -59,6 +62,9 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
} }
/**
* @codeCoverageIgnore
*/
public function ajax_selected_order() public function ajax_selected_order()
{ {
$ajax_url = admin_url('admin-ajax.php'); $ajax_url = admin_url('admin-ajax.php');
@ -140,7 +146,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
'placeholder' => __( 'Insert the Online consultant code here', 'retailcrm' ) 'placeholder' => __( 'Insert the Online consultant code here', 'retailcrm' )
); );
$this->form_fields[] = array( $this->form_fields['catalog_options'] = array(
'title' => __( 'Catalog settings', 'retailcrm' ), 'title' => __( 'Catalog settings', 'retailcrm' ),
'type' => 'heading', 'type' => 'heading',
'description' => '', 'description' => '',
@ -521,7 +527,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/** /**
* Debug information * Debug information
*/ */
$this->form_fields[] = array( $this->form_fields['debug-info'] = array(
'title' => __('Debug information', 'retailcrm'), 'title' => __('Debug information', 'retailcrm'),
'type' => 'heading', 'type' => 'heading',
'class' => 'debug_info_options' 'class' => 'debug_info_options'
@ -549,6 +555,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
* @param array $data * @param array $data
* *
* @return string * @return string
*
* @codeCoverageIgnore
*/ */
public function generate_button_html($key, $data) public function generate_button_html($key, $data)
{ {
@ -590,6 +598,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
* @param array $data * @param array $data
* *
* @return string * @return string
*
* @codeCoverageIgnore
*/ */
public function generate_heading_html($key, $data) public function generate_heading_html($key, $data)
{ {
@ -616,8 +626,10 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/** /**
* Returns the original value for the online_consultant field (ignores woocommerce validation) * Returns the original value for the online_consultant field (ignores woocommerce validation)
*
* @param $key * @param $key
* @param $value * @param $value
*
* @return string * @return string
*/ */
public function validate_online_assistant_field($key, $value) public function validate_online_assistant_field($key, $value)
@ -637,6 +649,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
* @param string $key * @param string $key
* @param string $value * @param string $value
* *
* @codeCoverageIgnore
*
* @return string * @return string
*/ */
public function validate_api_url_field($key, $value) public function validate_api_url_field($key, $value)
@ -664,6 +678,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
* @param string $key * @param string $key
* @param string $value * @param string $value
* *
* @codeCoverageIgnore
*
* @return string * @return string
*/ */
public function validate_api_key_field($key, $value) public function validate_api_key_field($key, $value)
@ -696,6 +712,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
* @param string $key * @param string $key
* @param string $value * @param string $value
* *
* @codeCoverageIgnore
*
* @return string * @return string
*/ */
public function validate_whatsapp_number_field($key, $value) public function validate_whatsapp_number_field($key, $value)
@ -717,6 +735,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/** /**
* Scritp show|hide block settings * Scritp show|hide block settings
*
* @codeCoverageIgnore
*/ */
function show_blocks() function show_blocks()
{ {
@ -744,6 +764,8 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
/** /**
* Add button in admin * Add button in admin
*
* @codeCoverageIgnore
*/ */
function add_retailcrm_button() { function add_retailcrm_button() {
global $wp_admin_bar; global $wp_admin_bar;
@ -777,4 +799,4 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
) )
); );
} }
} }

View File

@ -18,21 +18,9 @@ if (!class_exists('WC_Retailcrm_Base')) {
*/ */
class WC_Retailcrm_Base extends WC_Retailcrm_Abstracts_Settings class WC_Retailcrm_Base extends WC_Retailcrm_Abstracts_Settings
{ {
/** @var string */
protected $api_url;
/** @var string */
protected $api_key;
/** @var \WC_Retailcrm_Proxy|WC_Retailcrm_Client_V4|WC_Retailcrm_Client_V5|bool */ /** @var \WC_Retailcrm_Proxy|WC_Retailcrm_Client_V4|WC_Retailcrm_Client_V5|bool */
protected $apiClient; protected $apiClient;
/** @var mixed */
protected $order_item;
/** @var mixed */
protected $order_address;
/** @var \WC_Retailcrm_Customers */ /** @var \WC_Retailcrm_Customers */
protected $customers; protected $customers;
@ -118,7 +106,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('retailcrm_deactivate', array($this, 'deactivate')); add_action('retailcrm_deactivate', array($this, 'deactivate'));
} }
/** /**
* Init settings fields * Init settings fields
*/ */
@ -128,7 +115,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->init_settings(); $this->init_settings();
} }
/** /**
* @param $settings * @param $settings
* *
@ -167,7 +153,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
return $settings; return $settings;
} }
/**
* Generate ICML
*
* @codeCoverageIgnore Check in another tests
*/
public function generate_icml() public function generate_icml()
{ {
/* /*
@ -212,9 +202,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
$retailCrmIcml->generate(); $retailCrmIcml->generate();
} }
/** /**
* Get history * Get history
*
* @codeCoverageIgnore Check in another tests
*/ */
public function retailcrm_history_get() public function retailcrm_history_get()
{ {
@ -222,18 +213,20 @@ if (!class_exists('WC_Retailcrm_Base')) {
$retailcrm_history->getHistory(); $retailcrm_history->getHistory();
} }
/** /**
* @param int $order_id * @param int $order_id
*
* @codeCoverageIgnore Check in another tests
*/ */
public function retailcrm_process_order($order_id) public function retailcrm_process_order($order_id)
{ {
$this->orders->orderCreate($order_id); $this->orders->orderCreate($order_id);
} }
/** /**
* Load stock from retailCRM * Load stock from retailCRM
*
* @codeCoverageIgnore Check in another tests
*/ */
public function load_stocks() public function load_stocks()
{ {
@ -241,10 +234,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
$inventories->updateQuantity(); $inventories->updateQuantity();
} }
/** /**
* Upload selected orders * Upload selected orders
* *
* @codeCoverageIgnore Check in another tests
*
* @return void * @return void
*/ */
public function order_upload() public function order_upload()
@ -252,9 +246,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->uploader->uploadSelectedOrders(); $this->uploader->uploadSelectedOrders();
} }
/** /**
* Upload archive customers and order to retailCRM * Upload archive customers and order to retailCRM
*
* @codeCoverageIgnore Check in another tests
*/ */
public function upload_to_crm() public function upload_to_crm()
{ {
@ -268,12 +263,12 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Create customer in retailCRM * Create customer in retailCRM
* *
* @param int $customer_id * @param int $customer_id
* *
* @codeCoverageIgnore There is a task for analysis
* @return void * @return void
* @throws \Exception * @throws \Exception
*/ */
@ -330,9 +325,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Edit customer in retailCRM * Edit customer in retailCRM
*
* @codeCoverageIgnore Check in another tests
*
* @param int $customer_id * @param int $customer_id
*/ */
public function update_customer($customer_id) public function update_customer($customer_id)
@ -348,10 +345,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->customers->updateCustomer($customer_id); $this->customers->updateCustomer($customer_id);
} }
/** /**
* Create order in retailCRM from admin panel * Create order in retailCRM from admin panel
* *
* @codeCoverageIgnore Check in another tests
*
* @param int $order_id * @param int $order_id
*/ */
public function create_order($order_id) public function create_order($order_id)
@ -361,10 +359,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Edit order in retailCRM * Edit order in retailCRM
* *
* @codeCoverageIgnore Check in another tests
*
* @param int $order_id * @param int $order_id
* *
* @throws \Exception * @throws \Exception
@ -378,7 +377,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->orders->updateOrder($order_id); $this->orders->updateOrder($order_id);
} }
/** /**
* Init google analytics code * Init google analytics code
*/ */
@ -392,9 +390,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Google analytics send code * Google analytics send code
*
* @codeCoverageIgnore Check in another tests
*/ */
public function send_analytics() public function send_analytics()
{ {
@ -406,9 +405,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Daemon collector * Daemon collector
*
* @codeCoverageIgnore Check in another tests
*/ */
public function initialize_daemon_collector() public function initialize_daemon_collector()
{ {
@ -420,7 +420,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Initialize online consultant * Initialize online consultant
*/ */
@ -431,10 +430,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* In this method we include files in admin WP * In this method we include files in admin WP
* *
* @codeCoverageIgnore
*
* @return void * @return void
*/ */
public function include_files_for_admin() public function include_files_for_admin()
@ -443,10 +443,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->include_js_scripts_for_admin(); $this->include_js_scripts_for_admin();
} }
/** /**
* In this method we include CSS file * In this method we include CSS file
* *
* @codeCoverageIgnore
*
* @return void * @return void
*/ */
private function include_css_files_for_admin() private function include_css_files_for_admin()
@ -462,10 +463,11 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_enqueue_style('retailcrm-debug-info-style'); wp_enqueue_style('retailcrm-debug-info-style');
} }
/** /**
* In this method we include JS scripts. * In this method we include JS scripts.
* *
* @codeCoverageIgnore
*
* @return void * @return void
*/ */
private function include_js_scripts_for_admin() private function include_js_scripts_for_admin()
@ -479,9 +481,12 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_enqueue_script('retailcrm-cron-info', $path . 'retailcrm-export.js', '', '', true); wp_enqueue_script('retailcrm-cron-info', $path . 'retailcrm-export.js', '', '', true);
} }
/** /**
* Include style for WhatsApp icon * Include style for WhatsApp icon
*
* @codeCoverageIgnore
*
* @return void
*/ */
public function include_whatsapp_icon_style() public function include_whatsapp_icon_style()
{ {
@ -489,7 +494,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_enqueue_style('whatsapp_icon_style'); wp_enqueue_style('whatsapp_icon_style');
} }
/** /**
* Initialize WhatsApp * Initialize WhatsApp
*/ */
@ -514,7 +518,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
} }
} }
/** /**
* Return count upload data * Return count upload data
*/ */
@ -530,7 +533,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_die(); wp_die();
} }
/** /**
* Return time work next cron * Return time work next cron
*/ */
@ -562,7 +564,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_die(); wp_die();
} }
/** /**
* Get retailcrm api client * Get retailcrm api client
* *
@ -581,7 +582,6 @@ if (!class_exists('WC_Retailcrm_Base')) {
return false; return false;
} }
/** /**
* Deactivate module in marketplace retailCRM * Deactivate module in marketplace retailCRM
* *

View File

@ -51,19 +51,13 @@ if (!class_exists('WC_Retailcrm_Customers')) :
} }
/** /**
* setCustomerAddress * Return corporate customer
* *
* @param $address * @return array
*
* @return $this
*/ */
public function setCustomerAddress($address) public function getCorporateCustomer()
{ {
if ($address instanceof WC_Retailcrm_Customer_Address) { return $this->customerCorporate;
$this->customer_address = $address;
}
return $this;
} }
/** /**
@ -201,11 +195,13 @@ if (!class_exists('WC_Retailcrm_Customers')) :
} }
/** /**
* Create new address in corporate customer (if needed) * Create new address in corporate customer (if needed).
* *
* @param int $corporateId * @param int $corporateId
* @param \WC_Customer $customer * @param \WC_Customer $customer
* @param \WC_Order|null $order * @param \WC_Order|null $order
*
* @return bool
*/ */
public function fillCorporateAddress($corporateId, $customer, $order = null) public function fillCorporateAddress($corporateId, $customer, $order = null)
{ {
@ -213,7 +209,6 @@ if (!class_exists('WC_Retailcrm_Customers')) :
$builder = new WC_Retailcrm_Customer_Corporate_Address(); $builder = new WC_Retailcrm_Customer_Corporate_Address();
$newAddress = $builder $newAddress = $builder
->setIsMain(false) ->setIsMain(false)
->setExplicitIsMain(false)
->build($customer, $order) ->build($customer, $order)
->get_data(); ->get_data();
@ -225,7 +220,7 @@ if (!class_exists('WC_Retailcrm_Customers')) :
'id' 'id'
); );
if ($addresses && $addresses->isSuccessful() && $addresses->offsetExists('addresses')) { if (!empty($addresses['addresses']) && $addresses->isSuccessful()) {
foreach ($addresses['addresses'] as $address) { foreach ($addresses['addresses'] as $address) {
foreach ($newAddress as $field => $value) { foreach ($newAddress as $field => $value) {
if (isset($address[$field]) && $address[$field] != $value) { if (isset($address[$field]) && $address[$field] != $value) {
@ -249,6 +244,8 @@ if (!class_exists('WC_Retailcrm_Customers')) :
$this->retailcrm->getSingleSiteForKey() $this->retailcrm->getSingleSiteForKey()
); );
} }
return $found;
} }
/** /**
@ -261,7 +258,7 @@ if (!class_exists('WC_Retailcrm_Customers')) :
*/ */
protected function fillCorporateCustomer($response) protected function fillCorporateCustomer($response)
{ {
if (!$response->isSuccessful() || $response->isSuccessful() && !$response->offsetExists('id')) { if ((empty($response) || !$response->isSuccessful()) && !$response->offsetExists('id')) {
return null; return null;
} }

View File

@ -69,7 +69,7 @@ if (!class_exists('WC_Retailcrm_Google_Analytics')) {
$order_id = wc_get_order_id_by_order_key($_GET['key']); $order_id = wc_get_order_id_by_order_key($_GET['key']);
$order = wc_get_order($order_id); $order = wc_get_order($order_id);
if (!$order) { if (is_object($order) === false) {
return $js; return $js;
} }

View File

@ -35,9 +35,6 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
/** @var string */ /** @var string */
protected $bindField = 'externalId'; protected $bindField = 'externalId';
/** @var WC_Retailcrm_Order_Item */
protected $orderItem;
/** /**
* WC_Retailcrm_History constructor. * WC_Retailcrm_History constructor.
* *
@ -49,7 +46,8 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
{ {
$this->retailcrmSettings = get_option(WC_Retailcrm_Base::$option_key); $this->retailcrmSettings = get_option(WC_Retailcrm_Base::$option_key);
if (isset($this->retailcrmSettings['bind_by_sku']) if (
isset($this->retailcrmSettings['bind_by_sku'])
&& $this->retailcrmSettings['bind_by_sku'] == WC_Retailcrm_Base::YES && $this->retailcrmSettings['bind_by_sku'] == WC_Retailcrm_Base::YES
) { ) {
$this->bindField = 'xmlId'; $this->bindField = 'xmlId';
@ -78,23 +76,29 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$ordersSinceId = get_option('retailcrm_orders_history_since_id'); $ordersSinceId = get_option('retailcrm_orders_history_since_id');
$customersSinceId = get_option('retailcrm_customers_history_since_id'); $customersSinceId = get_option('retailcrm_customers_history_since_id');
// @codeCoverageIgnoreStart
// TODO: There is a task to analyze the work of getting history by date
if (!$ordersSinceId && isset($this->retailcrmSettings['history_orders'])) { if (!$ordersSinceId && isset($this->retailcrmSettings['history_orders'])) {
$this->startDateOrders = new DateTime($this->retailcrmSettings['history_orders']); $this->startDateOrders = new DateTime($this->retailcrmSettings['history_orders']);
} }
if (!$customersSinceId && isset($this->retailcrmSettings['history_customers'])) { if (!$customersSinceId && isset($this->retailcrmSettings['history_customers'])) {
$this->startDateCustomers = new DateTime($this->retailcrmSettings['history_customers']); $this->startDateCustomers = new DateTime($this->retailcrmSettings['history_customers']);
} }
// @codeCoverageIgnoreEnd
try { try {
$this->customersHistory($this->startDateCustomers->format('Y-m-d H:i:s'), $customersSinceId); $this->customersHistory($this->startDateCustomers->format('Y-m-d H:i:s'), $customersSinceId);
$this->ordersHistory($this->startDateOrders->format('Y-m-d H:i:s'), $ordersSinceId); $this->ordersHistory($this->startDateOrders->format('Y-m-d H:i:s'), $ordersSinceId);
// @codeCoverageIgnoreStart
} catch (\Exception $exception) { } catch (\Exception $exception) {
WC_Retailcrm_Logger::add( WC_Retailcrm_Logger::add(
sprintf("[%s] - %s", $exception->getMessage(), sprintf("[%s] - %s", $exception->getMessage(),
'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()) 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine())
); );
} }
// @codeCoverageIgnoreEnd
} }
/** /**
@ -132,6 +136,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled customers history:', $customers)); WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled customers history:', $customers));
foreach ($customers as $crmCustomer) { foreach ($customers as $crmCustomer) {
// Only update customers, if customer not exist in WP - skip this customer !
if (!isset($crmCustomer['externalId'])) { if (!isset($crmCustomer['externalId'])) {
continue; continue;
} }
@ -139,6 +144,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
try { try {
$builder->reset(); $builder->reset();
// @codeCoverageIgnoreStart
if (!$builder->loadExternalId($crmCustomer['externalId'])) { if (!$builder->loadExternalId($crmCustomer['externalId'])) {
WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf(
'Customer with id=%s is not found in the DB, skipping...', 'Customer with id=%s is not found in the DB, skipping...',
@ -146,6 +152,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
)); ));
continue; continue;
} }
// @codeCoverageIgnoreEnd
$wcCustomer = $builder $wcCustomer = $builder
->setData($crmCustomer) ->setData($crmCustomer)
@ -157,6 +164,8 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
} }
WC_Retailcrm_Logger::debug(__METHOD__, array('Updated WC_Customer:', $wcCustomer)); WC_Retailcrm_Logger::debug(__METHOD__, array('Updated WC_Customer:', $wcCustomer));
// @codeCoverageIgnoreStart
} catch (\Exception $exception) { } catch (\Exception $exception) {
WC_Retailcrm_Logger::error(sprintf( WC_Retailcrm_Logger::error(sprintf(
'Error while trying to process history: %s', 'Error while trying to process history: %s',
@ -169,6 +178,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
)); ));
WC_Retailcrm_Logger::error($exception->getTraceAsString()); WC_Retailcrm_Logger::error($exception->getTraceAsString());
} }
// @codeCoverageIgnoreEnd
} }
update_option('retailcrm_customers_history_since_id', $lastChange['id']); update_option('retailcrm_customers_history_since_id', $lastChange['id']);
@ -206,6 +216,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
if (!empty($history)) { if (!empty($history)) {
$lastChange = end($history); $lastChange = end($history);
$historyAssembly = WC_Retailcrm_History_Assembler::assemblyOrder($history); $historyAssembly = WC_Retailcrm_History_Assembler::assemblyOrder($history);
WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled orders history:', $historyAssembly)); WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled orders history:', $historyAssembly));
WC_Retailcrm_Plugin::$history_run = true; WC_Retailcrm_Plugin::$history_run = true;
@ -226,8 +237,10 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$wcOrder = wc_get_order($wcOrderId); $wcOrder = wc_get_order($wcOrderId);
if ($wcOrder instanceof WC_Order) { if ($wcOrder instanceof WC_Order) {
$this->update_total($wcOrder); $wcOrder->calculate_totals();
} }
// @codeCoverageIgnoreStart
} catch (Exception $exception) { } catch (Exception $exception) {
WC_Retailcrm_Logger::add( WC_Retailcrm_Logger::add(
sprintf("[%s] - %s", $exception->getMessage(), sprintf("[%s] - %s", $exception->getMessage(),
@ -236,6 +249,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
continue; continue;
} }
// @codeCoverageIgnoreEnd
} }
update_option('retailcrm_orders_history_since_id', $lastChange['id']); update_option('retailcrm_orders_history_since_id', $lastChange['id']);
@ -306,18 +320,6 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
return true; return true;
} }
/**
* Calculate totals in order
*
* @param WC_Order $order
*
* @return void
*/
protected function update_total($order)
{
$order->calculate_totals();
}
/** /**
* Update order in WC * Update order in WC
* *
@ -366,13 +368,17 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
} }
if (isset($order['contact']['address'])) { if (isset($order['contact']['address'])) {
var_dump('test');
$billingAddress = $order['contact']['address']; $billingAddress = $order['contact']['address'];
$wcOrder->set_billing_state(self::arrayValue($billingAddress, 'region', '')); // @codeCoverageIgnoreStart
$wcOrder->set_billing_postcode(self::arrayValue($billingAddress, 'index', '')); // TODO: There is a task to analyze the work set billing address in WC order
$wcOrder->set_billing_country(self::arrayValue($billingAddress, 'country', '')); $wcOrder->set_billing_state(self::arrayValue($billingAddress, 'region'));
$wcOrder->set_billing_city(self::arrayValue($billingAddress, 'city', '')); $wcOrder->set_billing_postcode(self::arrayValue($billingAddress, 'index'));
$wcOrder->set_billing_address_1(self::arrayValue($billingAddress, 'text', '')); $wcOrder->set_billing_country(self::arrayValue($billingAddress, 'country'));
$wcOrder->set_billing_city(self::arrayValue($billingAddress, 'city'));
$wcOrder->set_billing_address_1(self::arrayValue($billingAddress, 'text'));
// @codeCoverageIgnoreEnd
} }
} }
@ -885,6 +891,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
if (!empty($crmOrder) && isset($crmOrder['items'][$item['id']])) { if (!empty($crmOrder) && isset($crmOrder['items'][$item['id']])) {
$woocommerceId = self::getItemWoocommerceId($crmOrder['items'][$item['id']]); $woocommerceId = self::getItemWoocommerceId($crmOrder['items'][$item['id']]);
} else { } else {
// @codeCoverageIgnoreStart
WC_Retailcrm_Logger::add( WC_Retailcrm_Logger::add(
sprintf( sprintf(
"Order externalId=`%s`: item doesn't have woocomerceId, skipping... (item id=`%s`)", "Order externalId=`%s`: item doesn't have woocomerceId, skipping... (item id=`%s`)",
@ -893,6 +900,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
) )
); );
continue; continue;
// @codeCoverageIgnoreEnd
} }
} else { } else {
$woocommerceId = self::getItemWoocommerceId($order['items'][$item['id']]); $woocommerceId = self::getItemWoocommerceId($order['items'][$item['id']]);

View File

@ -44,11 +44,11 @@ if (!class_exists('WC_Retailcrm_Inventories')) :
* *
* @return mixed * @return mixed
*/ */
public function load_stocks() protected function load_stocks()
{ {
$success = array(); $success = array();
if (!$this->retailcrm) { if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null; return null;
} }
@ -56,17 +56,17 @@ if (!class_exists('WC_Retailcrm_Inventories')) :
$variationProducts = array(); $variationProducts = array();
do { do {
/** @var WC_Retailcrm_Response $result */ /** @var WC_Retailcrm_Response $response */
$result = $this->retailcrm->storeInventories(array(), $page, 250); $response = $this->retailcrm->storeInventories(array(), $page, 250);
if (!$result->isSuccessful()) { if (empty($response) || !$response->isSuccessful()) {
return null; return null;
} }
$totalPageCount = $result['pagination']['totalPageCount']; $totalPageCount = $response['pagination']['totalPageCount'];
$page++; $page++;
foreach ($result['offers'] as $offer) { foreach ($response['offers'] as $offer) {
if (isset($offer[$this->bind_field])) { if (isset($offer[$this->bind_field])) {
$product = retailcrm_get_wc_product($offer[$this->bind_field], $this->retailcrm_settings); $product = retailcrm_get_wc_product($offer[$this->bind_field], $this->retailcrm_settings);
@ -96,7 +96,7 @@ if (!class_exists('WC_Retailcrm_Inventories')) :
if (is_object($variationProduct)) { if (is_object($variationProduct)) {
$variationProduct->set_manage_stock(true); $variationProduct->set_manage_stock(true);
$variationProduct->set_stock($quantity); $variationProduct->set_stock_quantity($quantity);
$success[] = $variationProduct->save(); $success[] = $variationProduct->save();
} }
} }
@ -121,3 +121,4 @@ if (!class_exists('WC_Retailcrm_Inventories')) :
} }
} }
endif; endif;

View File

@ -84,7 +84,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
try { try {
$response = $this->retailcrm->ordersCreate($this->order); $response = $this->retailcrm->ordersCreate($this->order);
if ($response instanceof WC_Retailcrm_Response) { if ($response instanceof WC_Retailcrm_Proxy) {
if ($response->isSuccessful()) { if ($response->isSuccessful()) {
return $wcOrder; return $wcOrder;
} }
@ -138,6 +138,8 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
} }
} }
// @codeCoverageIgnoreStart
// TODO: There is a task for analysis
if ($update && $customerWasChanged) { if ($update && $customerWasChanged) {
$firstName = $wcOrder->get_shipping_first_name(); $firstName = $wcOrder->get_shipping_first_name();
$lastName = $wcOrder->get_shipping_last_name(); $lastName = $wcOrder->get_shipping_last_name();
@ -145,6 +147,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$this->order['firstName'] = $firstName; $this->order['firstName'] = $firstName;
$this->order['lastName'] = $lastName; $this->order['lastName'] = $lastName;
} }
// @codeCoverageIgnoreEnd
return true; return true;
} }
@ -203,12 +206,27 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
); );
$this->order['customer']['id'] = $corporateId; $this->order['customer']['id'] = $corporateId;
} else { } else {
$this->customers->fillCorporateAddress( // Testing of this method occurs in customers tests.
// @codeCoverageIgnoreStart
$addressFound = $this->customers->fillCorporateAddress(
$crmCorporate['id'], $crmCorporate['id'],
new WC_Customer($wcCustomerId), new WC_Customer($wcCustomerId),
$wcOrder $wcOrder
); );
// If address not found create new address.
if (!$addressFound) {
WC_Retailcrm_Logger::add(
sprintf(
'[%d] => %s',
$this->order['customer']['id'],
'Notification: Create new address for corporate customer'
)
);
}
$this->order['customer']['id'] = $crmCorporate['id']; $this->order['customer']['id'] = $crmCorporate['id'];
// @codeCoverageIgnoreEnd
} }
$companiesResponse = $this->retailcrm->customersCorporateCompanies( $companiesResponse = $this->retailcrm->customersCorporateCompanies(
@ -511,7 +529,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
} }
$customerWasChanged = self::isCorporateOrder($wcOrder) != self::isCorporateCrmOrder($crmOrder); $customerWasChanged = self::isCorporateOrder($wcOrder) != self::isCorporateCrmOrder($crmOrder);
$synchronizableUserData = self::isCorporateCrmOrder($crmOrder) $synchronizableUserData = (self::isCorporateCrmOrder($crmOrder) && isset($crmOrder['contact']))
? $crmOrder['contact'] : $crmOrder['customer']; ? $crmOrder['contact'] : $crmOrder['customer'];
if (!$customerWasChanged) { if (!$customerWasChanged) {
@ -523,11 +541,13 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
} }
} }
if (isset($synchronizableUserData['externalId']) if (
isset($synchronizableUserData['externalId'])
&& $synchronizableUserData['externalId'] != $wcOrder->get_customer_id() && $synchronizableUserData['externalId'] != $wcOrder->get_customer_id()
) { ) {
$customerWasChanged = true; $customerWasChanged = true;
} elseif (isset($synchronizableUserData['email']) } elseif (
isset($synchronizableUserData['email'])
&& $synchronizableUserData['email'] != $wcOrder->get_billing_email() && $synchronizableUserData['email'] != $wcOrder->get_billing_email()
) { ) {
$customerWasChanged = true; $customerWasChanged = true;

View File

@ -1,16 +1,17 @@
<?php <?php
class WC_Retailcrm_Plugin { class WC_Retailcrm_Plugin
{
public $file; public $file;
public static $history_run = false; public static $history_run = false;
private static $instance = null; private static $instance = null;
const MARKETPLACE_LOGO = 'https://s3.eu-central-1.amazonaws.com/retailcrm-billing/images/5b69ce4bda663-woocommercesvg2.svg'; const MARKETPLACE_LOGO = 'https://s3.eu-central-1.amazonaws.com/retailcrm-billing/images/5b69ce4bda663-woocommercesvg2.svg';
const INTEGRATION_CODE = 'woocommerce'; const INTEGRATION_CODE = 'woocommerce';
public static function getInstance($file) { public static function getInstance($file)
{
if (self::$instance === null) { if (self::$instance === null) {
self::$instance = new self($file); self::$instance = new self($file);
} }
@ -18,13 +19,20 @@ class WC_Retailcrm_Plugin {
return self::$instance; return self::$instance;
} }
private function __construct($file) { /**
* @param $file
*
* @codeCoverageIgnore
*/
private function __construct($file)
{
$this->file = $file; $this->file = $file;
add_filter('cron_schedules', array($this, 'filter_cron_schedules'), 10, 1); add_filter('cron_schedules', array($this, 'filter_cron_schedules'), 10, 1);
} }
public function filter_cron_schedules($schedules) { public function filter_cron_schedules($schedules)
{
return array_merge( return array_merge(
$schedules, $schedules,
array( array(
@ -44,16 +52,22 @@ class WC_Retailcrm_Plugin {
); );
} }
public function register_activation_hook() { public function register_activation_hook()
{
register_activation_hook($this->file, array($this, 'activate')); register_activation_hook($this->file, array($this, 'activate'));
} }
public function register_deactivation_hook() { public function register_deactivation_hook()
{
register_deactivation_hook($this->file, array($this, 'deactivate')); register_deactivation_hook($this->file, array($this, 'deactivate'));
} }
public function activate() { /**
if (!class_exists( 'WC_Integration' ) ) { * @codeCoverageIgnore
*/
public function activate()
{
if (!class_exists('WC_Integration')) {
add_action('admin_notices', array(new WC_Integration_Retailcrm(), 'woocommerce_missing_notice')); add_action('admin_notices', array(new WC_Integration_Retailcrm(), 'woocommerce_missing_notice'));
return; return;
@ -71,7 +85,8 @@ class WC_Retailcrm_Plugin {
$retailcrm_icml->generate(); $retailcrm_icml->generate();
} }
public function deactivate() { public function deactivate()
{
do_action('retailcrm_deactivate'); do_action('retailcrm_deactivate');
if (wp_next_scheduled('retailcrm_icml')) { if (wp_next_scheduled('retailcrm_icml')) {
@ -96,9 +111,10 @@ class WC_Retailcrm_Plugin {
* *
* @return boolean * @return boolean
*/ */
public static function integration_module($api_client, $client_id, $active = true) { public static function integration_module($api_client, $client_id, $active = true)
{
if (!$api_client) { if (!$api_client instanceof WC_Retailcrm_Proxy) {
return false; return false;
} }
@ -116,15 +132,7 @@ class WC_Retailcrm_Plugin {
$response = $api_client->integrationModulesEdit($configuration); $response = $api_client->integrationModulesEdit($configuration);
if (!$response) { return !empty($response) && $response->isSuccessful();
return false;
}
if (!empty($response) && $response->isSuccessful()) {
return true;
}
return false;
} }
/** /**
@ -147,7 +155,8 @@ class WC_Retailcrm_Plugin {
? self::clearArray($node) ? self::clearArray($node)
: $node; : $node;
if ($result[$index] === '' if (
$result[$index] === ''
|| $result[$index] === null || $result[$index] === null
|| (is_array($result[$index]) && count($result[$index]) < 1) || (is_array($result[$index]) && count($result[$index]) < 1)
) { ) {
@ -158,22 +167,6 @@ class WC_Retailcrm_Plugin {
return $result; return $result;
} }
/**
* Returns WC_Customer by id. Returns null if there's no such customer.
*
* @param int $id
*
* @return \WC_Customer|null
*/
public static function getWcCustomerById($id)
{
try {
return new WC_Customer($id);
} catch (\Exception $exception) {
return null;
}
}
/** /**
* Check running history * Check running history
* *

View File

@ -37,7 +37,6 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
*/ */
private $customers; private $customers;
/** /**
* WC_Retailcrm_Uploader constructor. * WC_Retailcrm_Uploader constructor.
* *
@ -52,7 +51,6 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
$this->customers = $customers; $this->customers = $customers;
} }
/** /**
* Uploads selected order in CRM * Uploads selected order in CRM
* *
@ -63,16 +61,15 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
{ {
$response = filter_input(INPUT_GET, 'order_ids_retailcrm'); $response = filter_input(INPUT_GET, 'order_ids_retailcrm');
if (empty($response) === false) { if (false === empty($response)) {
$ids = array_unique(explode(',', $response)); $ids = array_unique(explode(',', $response));
if (empty($ids) === false) { if (false === empty($ids)) {
$this->uploadArchiveOrders(0, $ids); $this->uploadArchiveOrders(0, $ids);
} }
} }
} }
/** /**
* Uploads archive order in CRM * Uploads archive order in CRM
* *
@ -95,8 +92,10 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
$orderId = $dataOrder->ID; $orderId = $dataOrder->ID;
$errorMessage = $this->orders->orderCreate($orderId); $errorMessage = $this->orders->orderCreate($orderId);
if (is_string($errorMessage) === true) { if (true === is_string($errorMessage)) {
$errorMessage = empty($errorMessage) === true ? 'Order exist. External id: ' . $orderId : $errorMessage; $errorMessage = empty($errorMessage) === true
? 'Order exist. External id: ' . $orderId
: $errorMessage;
$uploadErrors[$orderId] = $errorMessage; $uploadErrors[$orderId] = $errorMessage;
} }
} }
@ -106,7 +105,6 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
return array(); return array();
} }
/** /**
* Uploads archive customer in CRM * Uploads archive customer in CRM
* *
@ -123,7 +121,7 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
$users = $this->getCmsUsers($page); $users = $this->getCmsUsers($page);
if (empty($users) === false) { if (false === empty($users)) {
$dataCustomers = array(); $dataCustomers = array();
foreach ($users as $user) { foreach ($users as $user) {
@ -142,7 +140,6 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
return $dataCustomers; return $dataCustomers;
} }
/** /**
* Return orders ids * Return orders ids
* *
@ -164,7 +161,6 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
); );
} }
/** /**
* Return count orders * Return count orders
* *
@ -176,7 +172,7 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
$result = $wpdb->get_results("SELECT COUNT(ID) as `count` FROM $wpdb->posts WHERE post_type = 'shop_order'"); $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 empty($result[0]->count) === false ? (int) $result[0]->count : 0;
} }
@ -217,6 +213,8 @@ if (class_exists('WC_Retailcrm_Uploader') === false) {
* @param array $errors Id order - key and message error - value. * @param array $errors Id order - key and message error - value.
* *
* @return void * @return void
*
* @codeCoverageIgnore
*/ */
private function logOrdersUploadErrors($errors) private function logOrdersUploadErrors($errors)
{ {

View File

@ -110,7 +110,7 @@ class WC_Retailcrm_Customer_Switcher implements WC_Retailcrm_Builder_Interface
); );
if (isset($newCustomer['externalId'])) { if (isset($newCustomer['externalId'])) {
$wcCustomer = WC_Retailcrm_Plugin::getWcCustomerById($newCustomer['externalId']); $wcCustomer = new WC_Customer($newCustomer['externalId']);
if (!empty($wcCustomer)) { if (!empty($wcCustomer)) {
$wcOrder->set_customer_id($wcCustomer->get_id()); $wcOrder->set_customer_id($wcCustomer->get_id());

View File

@ -10,6 +10,8 @@
if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')): if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')):
/** /**
* Class WC_Retailcrm_Logger * Class WC_Retailcrm_Logger
*
* @codeCoverageIgnore
*/ */
class WC_Retailcrm_Logger class WC_Retailcrm_Logger
{ {

View File

@ -17,9 +17,6 @@ class WC_Retailcrm_Customer_Corporate_Address extends WC_Retailcrm_Abstracts_Add
/** @var bool $isMain */ /** @var bool $isMain */
protected $isMain = true; protected $isMain = true;
/** @var bool $explicitIsMain */
protected $explicitIsMain;
/** /**
* @param bool $isMain * @param bool $isMain
* *
@ -31,17 +28,6 @@ class WC_Retailcrm_Customer_Corporate_Address extends WC_Retailcrm_Abstracts_Add
return $this; return $this;
} }
/**
* @param bool $explicitIsMain
*
* @return WC_Retailcrm_Customer_Corporate_Address
*/
public function setExplicitIsMain($explicitIsMain)
{
$this->explicitIsMain = $explicitIsMain;
return $this;
}
/** /**
* @param WC_Customer $customer * @param WC_Customer $customer
* @param \WC_Order|null $order * @param \WC_Order|null $order
@ -53,17 +39,13 @@ class WC_Retailcrm_Customer_Corporate_Address extends WC_Retailcrm_Abstracts_Add
$address = $this->getCustomerAddress($customer, $order); $address = $this->getCustomerAddress($customer, $order);
if (!empty($address)) { if (!empty($address)) {
if ($this->isMain) { $address['isMain'] = $this->isMain;
$address['isMain'] = true;
} elseif ($this->explicitIsMain) {
$address['isMain'] = false;
}
$corporateCustomerAddress = apply_filters( $corporateCustomerAddress = apply_filters(
'retailcrm_process_customer_corporate_address', 'retailcrm_process_customer_corporate_address',
WC_Retailcrm_Plugin::clearArray(array_merge( WC_Retailcrm_Plugin::clearArray(array_merge(
$address, $address,
array('isMain' => $address['isMain']) array('isMain' => $this->isMain)
)), )),
$customer $customer
); );
@ -73,7 +55,6 @@ class WC_Retailcrm_Customer_Corporate_Address extends WC_Retailcrm_Abstracts_Add
WC_Retailcrm_Logger::add('Error Corporate Customer address is empty'); WC_Retailcrm_Logger::add('Error Corporate Customer address is empty');
} }
return $this; return $this;
} }
} }

View File

@ -235,3 +235,4 @@ class WC_Retailcrm_WC_Customer_Builder extends WC_Retailcrm_Abstract_Builder
return true; return true;
} }
} }

View File

@ -1,10 +1,13 @@
<?php <?php
if ( ! defined( 'ABSPATH' ) ) { if (! defined('ABSPATH')) {
exit; // Exit if accessed directly exit; // Exit if accessed directly
} }
function get_wc_shipping_methods_by_zones($enhanced = false) { // @codeCoverageIgnoreStart
// TODO: There is a task to analyze the work
function get_wc_shipping_methods_by_zones($enhanced = false)
{
$result = array(); $result = array();
$shippingZones = WC_Shipping_Zones::get_zones(); $shippingZones = WC_Shipping_Zones::get_zones();
@ -51,8 +54,10 @@ function get_wc_shipping_methods_by_zones($enhanced = false) {
return $result; return $result;
} }
// @codeCoverageIgnoreEnd
function get_wc_shipping_methods() { function get_wc_shipping_methods()
{
$wc_shipping = WC_Shipping::instance(); $wc_shipping = WC_Shipping::instance();
$shipping_methods = $wc_shipping->get_shipping_methods(); $shipping_methods = $wc_shipping->get_shipping_methods();
@ -70,7 +75,8 @@ function get_wc_shipping_methods() {
return apply_filters('retailcrm_shipping_list', WC_Retailcrm_Plugin::clearArray($result)); return apply_filters('retailcrm_shipping_list', WC_Retailcrm_Plugin::clearArray($result));
} }
function retailcrm_get_delivery_service($method_id, $instance_id) { function retailcrm_get_delivery_service($method_id, $instance_id)
{
$shippings_by_zone = get_wc_shipping_methods_by_zones(true); $shippings_by_zone = get_wc_shipping_methods_by_zones(true);
$method = explode(':', $method_id); $method = explode(':', $method_id);
$method_id = $method[0]; $method_id = $method[0];
@ -89,8 +95,10 @@ function retailcrm_get_delivery_service($method_id, $instance_id) {
* *
* @return false|WC_Product|null * @return false|WC_Product|null
*/ */
function retailcrm_get_wc_product($id, $settings) { function retailcrm_get_wc_product($id, $settings)
if (isset($settings['bind_by_sku']) {
if (
isset($settings['bind_by_sku'])
&& $settings['bind_by_sku'] == WC_Retailcrm_Base::YES && $settings['bind_by_sku'] == WC_Retailcrm_Base::YES
) { ) {
$id = wc_get_product_id_by_sku($id); $id = wc_get_product_id_by_sku($id);
@ -104,8 +112,8 @@ function retailcrm_get_wc_product($id, $settings) {
* *
* @return bool * @return bool
*/ */
function retailcrm_is_debug() { function retailcrm_is_debug()
{
$options = get_option(WC_Retailcrm_Base::$option_key); $options = get_option(WC_Retailcrm_Base::$option_key);
if (isset($options['debug_mode']) === true && $options['debug_mode'] === WC_Retailcrm_Base::YES) { if (isset($options['debug_mode']) === true && $options['debug_mode'] === WC_Retailcrm_Base::YES) {
@ -122,10 +130,10 @@ function is_wplogin()
{ {
$ABSPATH_MY = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, ABSPATH); $ABSPATH_MY = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, ABSPATH);
return ((in_array($ABSPATH_MY.'wp-login.php', get_included_files()) return (
|| in_array($ABSPATH_MY.'wp-register.php', get_included_files())) (in_array($ABSPATH_MY . 'wp-login.php', get_included_files())
|| in_array($ABSPATH_MY . 'wp-register.php', get_included_files()))
|| (isset($_GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php') || (isset($_GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php')
|| $_SERVER['PHP_SELF']== '/wp-login.php' || $_SERVER['PHP_SELF'] == '/wp-login.php'
); );
} }

View File

@ -176,3 +176,4 @@ class WC_Retailcrm_Customer_Switcher_State
} }
} }
} }

View File

@ -14,8 +14,6 @@ class WC_Retailcrm_Order extends WC_Retailcrm_Abstracts_Data
/** @var bool */ /** @var bool */
public $is_new = true; public $is_new = true;
protected $filter_name = 'order';
protected $data = array( protected $data = array(
'externalId' => 0, 'externalId' => 0,
'status' => '', 'status' => '',
@ -74,7 +72,7 @@ class WC_Retailcrm_Order extends WC_Retailcrm_Abstracts_Data
'countryIso' => $order->get_shipping_country() 'countryIso' => $order->get_shipping_country()
); );
if ($data['countryIso'] == '--') { if ($data['countryIso'] == '--' || empty($data['countryIso'])) {
$countries = new WC_Countries(); $countries = new WC_Countries();
$data['countryIso'] = $countries->get_base_country(); $data['countryIso'] = $countries->get_base_country();
} }
@ -89,19 +87,6 @@ class WC_Retailcrm_Order extends WC_Retailcrm_Abstracts_Data
return $this; return $this;
} }
/**
* @param WC_Order $order
*/
protected function set_payment_data($order)
{
if ($order->get_payment_method() && isset($this->settings[$order->get_payment_method()])) {
$this->set_data_field('paymentType', $this->settings[$order->get_payment_method()]);
}
if ($order->is_paid()) {
$this->set_data_field('paymentStatus', 'paid');
}
}
/** /**
* @param WC_Order $order * @param WC_Order $order

View File

@ -2,10 +2,10 @@
Contributors: Simla.com Contributors: Simla.com
Donate link: https://www.simla.com Donate link: https://www.simla.com
Tags: Интеграция, Simla.com, simla Tags: Интеграция, Simla.com, simla
Requires PHP: 5.3 Requires PHP: 5.6
Requires at least: 5.3 Requires at least: 5.3
Tested up to: 5.8 Tested up to: 5.8
Stable tag: 4.3.8 Stable tag: 4.4.0
License: GPLv1 or later License: GPLv1 or later
License URI: http://www.gnu.org/licenses/gpl-1.0.html License URI: http://www.gnu.org/licenses/gpl-1.0.html
@ -82,6 +82,12 @@ Asegúrate de tener una clave API específica para cada tienda. Las siguientes i
== Changelog == == Changelog ==
= 4.4.0 =
* Migrating to PHP 5.6. We tested the module, improved performance, security and test coverage.
* Add validate countryIso. Fix bug with duplicate customer address
* Fix bugs in history
* Fix PHP warning and deprecated
* Add documentation for module
= 4.3.8 = = 4.3.8 =
* Updated logic work address * Updated logic work address

View File

@ -5,10 +5,10 @@
* Description: Integration plugin for WooCommerce & Simla.com * Description: Integration plugin for WooCommerce & Simla.com
* Author: RetailDriver LLC * Author: RetailDriver LLC
* Author URI: http://retailcrm.pro/ * Author URI: http://retailcrm.pro/
* Version: 4.3.8 * Version: 4.4.0
* Tested up to: 5.8 * Tested up to: 5.8
* WC requires at least: 3.0 * WC requires at least: 5.4
* WC tested up to: 5.4 * WC tested up to: 5.8
* Text Domain: retailcrm * Text Domain: retailcrm
*/ */
@ -20,6 +20,8 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
/** /**
* Class WC_Integration_Retailcrm * Class WC_Integration_Retailcrm
*
* @codeCoverageIgnore
*/ */
class WC_Integration_Retailcrm { class WC_Integration_Retailcrm {
const WOOCOMMERCE_SLUG = 'woocommerce'; const WOOCOMMERCE_SLUG = 'woocommerce';
@ -125,7 +127,6 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
require_once(self::checkCustomFile('include/class-wc-retailcrm-base.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/class-wc-retailcrm-uploader.php'));
require_once(self::checkCustomFile('include/functions.php')); require_once(self::checkCustomFile('include/functions.php'));
} }
/** /**

View File

@ -16,11 +16,12 @@
* *
* @link https://wordpress.org/plugins/woo-retailcrm/ * @link https://wordpress.org/plugins/woo-retailcrm/
* *
* @version 4.3.8 * @version 4.4.0
* *
* @package RetailCRM * @package RetailCRM
*/ */
// @codeCoverageIgnoreStart
if (!defined('ABSPATH')) { if (!defined('ABSPATH')) {
exit; // Exit if accessed directly exit; // Exit if accessed directly
} }
@ -45,3 +46,4 @@ $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = 'retailcrm_client_i
// Clear any cached data that has been removed // Clear any cached data that has been removed
wp_cache_flush(); wp_cache_flush();
// @codeCoverageIgnoreEnd

View File

@ -0,0 +1,52 @@
<?php
class WC_Retailcrm_Abstracts_Settings_Test extends WC_Retailcrm_Test_Case_Helper
{
/**
* @var WC_Retailcrm_Base
*/
protected $base;
public function setUp()
{
$this->base = new WC_Retailcrm_Base();
parent::setUp();
}
/**
* @param $checkout
*
* @dataProvider dataProviderAssistant
*/
public function test_validate_online_assistant_field($checkout)
{
$_POST['woocommerce_integration-retailcrm_online_assistant'] = $checkout;
$onlineAssistant = $this->base->validate_online_assistant_field('', '');
$this->assertInternalType('string', $onlineAssistant);
if (is_string($checkout)) {
$this->assertEquals('jscode', $onlineAssistant);
} else {
$this->assertEquals('', $onlineAssistant);
}
}
public function dataProviderAssistant()
{
return array(
array(
'checkout' => 'js\code'
),
array(
'checkout' => null
),
array(
'checkout' => array()
)
);
}
}

View File

@ -32,7 +32,6 @@ class WC_Retailcrm_Customer_Corporate_Address_Test extends WC_Retailcrm_Test_Cas
$customer_address = new WC_Retailcrm_Customer_Corporate_Address(); $customer_address = new WC_Retailcrm_Customer_Corporate_Address();
$data = $customer_address $data = $customer_address
->setIsMain(true) ->setIsMain(true)
->setExplicitIsMain(false)
->build($this->customer) ->build($this->customer)
->get_data(); ->get_data();
@ -69,7 +68,6 @@ class WC_Retailcrm_Customer_Corporate_Address_Test extends WC_Retailcrm_Test_Cas
$customer_address = new WC_Retailcrm_Customer_Corporate_Address(); $customer_address = new WC_Retailcrm_Customer_Corporate_Address();
$data = $customer_address $data = $customer_address
->setIsMain(false) ->setIsMain(false)
->setExplicitIsMain(true)
->build($this->customer) ->build($this->customer)
->get_data(); ->get_data();
@ -93,7 +91,6 @@ class WC_Retailcrm_Customer_Corporate_Address_Test extends WC_Retailcrm_Test_Cas
$customer_address = new WC_Retailcrm_Customer_Corporate_Address(); $customer_address = new WC_Retailcrm_Customer_Corporate_Address();
$data = $customer_address $data = $customer_address
->setIsMain(false) ->setIsMain(false)
->setExplicitIsMain(true)
->build(null) ->build(null)
->get_data(); ->get_data();

View File

@ -11,13 +11,29 @@
class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $customer;
public function setUp()
{
$this->customer = new WC_Customer();
$this->customer->set_first_name('Tester First Name');
$this->customer->set_last_name('Tester Last Name');
$this->customer->set_email(uniqid(md5(date('Y-m-d H:i:s'))) . '@mail.com');
$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();
}
/** /**
* @expectedException \RuntimeException * @expectedException \RuntimeException
*/ */
public function test_empty() public function test_empty()
{ {
$builder = new WC_Retailcrm_WC_Customer_Builder(); $builder = new WC_Retailcrm_WC_Customer_Builder();
$builder->build();
$this->assertEmpty($builder->build()->getResult());
} }
/** /**
@ -26,7 +42,8 @@ class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helpe
public function test_empty_array() public function test_empty_array()
{ {
$builder = new WC_Retailcrm_WC_Customer_Builder(); $builder = new WC_Retailcrm_WC_Customer_Builder();
$builder->setData(array())->build();
$this->assertEmpty($builder->setData(array())->build()->getResult());
} }
/** /**
@ -35,13 +52,14 @@ class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helpe
public function test_not_array() public function test_not_array()
{ {
$builder = new WC_Retailcrm_WC_Customer_Builder(); $builder = new WC_Retailcrm_WC_Customer_Builder();
$builder->setData(new stdClass())->build();
$this->assertEquals('test', $builder->setData('test')->build()->getResult());
} }
/** /**
* @dataProvider customerData * @dataProvider customerData
* *
* @param array $customerData * @param $customerData
*/ */
public function test_build($customerData) public function test_build($customerData)
{ {
@ -87,6 +105,133 @@ class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helpe
} }
} }
public function test_set_field()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$customerData = $this->customerData()[1]['customer'];
$wcCustomer = $builder
->setFirstName($customerData['firstName'])
->setLastName($customerData['lastName'])
->setEmail($customerData['email'])
->setExternalId($customerData['externalId'])
->setPhones($customerData['phones'])
->setAddress($customerData['address'])
->build()
->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals($customerData['firstName'], $wcCustomer->get_first_name());
$this->assertEquals($customerData['lastName'], $wcCustomer->get_last_name());
$this->assertEquals($customerData['email'], $wcCustomer->get_billing_email());
$this->assertEquals($customerData['phones'][0]['number'], $wcCustomer->get_billing_phone());
$address = $customerData['address'];
$this->assertEquals($address['region'], $wcCustomer->get_billing_state());
$this->assertEquals($address['index'], $wcCustomer->get_billing_postcode());
$this->assertEquals($address['country'], $wcCustomer->get_billing_country());
$this->assertEquals($address['city'], $wcCustomer->get_billing_city());
}
public function test_phone_string()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$customerData = $this->customerData()[1]['customer'];
$customerData['phones'] = '123454567';
$wcCustomer = $builder->setData($customerData)->build()->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals('123454567', $wcCustomer->get_billing_phone());
}
public function test_set_phone_string()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$customerData = $this->customerData()[1]['customer'];
$wcCustomer = $builder->setData($customerData)->setPhones('123456789')->build()->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals($customerData['phones'][0]['number'], $wcCustomer->get_billing_phone());
}
public function test_set_address_empty()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$customerData = $this->customerData()[1]['customer'];
$wcCustomer = $builder->setData($customerData)->setAddress(array())->build()->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEmpty($wcCustomer->get_billing_state());
$this->assertEmpty($wcCustomer->get_billing_postcode());
$this->assertEmpty($wcCustomer->get_billing_country());
$this->assertEmpty($wcCustomer->get_billing_city());
}
public function test_set_wc_customer()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$wcCustomer = $builder->setWcCustomer($this->customer)->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals($this->customer->get_id(), $wcCustomer->get_id());
$this->assertEquals($this->customer->get_first_name(), $wcCustomer->get_first_name());
$this->assertEquals($this->customer->get_last_name(), $wcCustomer->get_last_name());
$this->assertEquals($this->customer->get_billing_phone(), $wcCustomer->get_billing_phone());
$this->assertEquals($this->customer->get_email(), $wcCustomer->get_email());
}
public function test_set_not_wc_customer()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$wcCustomer = $builder->setWcCustomer(null)->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals(null, $wcCustomer->get_id());
$this->assertEquals(null, $wcCustomer->get_first_name());
$this->assertEquals(null, $wcCustomer->get_last_name());
$this->assertEquals(null, $wcCustomer->get_billing_phone());
$this->assertEquals(null, $wcCustomer->get_email());
}
public function test_load_wc_customer_by_id()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$isValidExternalId = $builder->loadExternalId($this->customer->get_id());
$wcCustomer = $builder->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals(true, $isValidExternalId);
$this->assertEquals($this->customer->get_id(), $wcCustomer->get_id());
$this->assertEquals($this->customer->get_first_name(), $wcCustomer->get_first_name());
$this->assertEquals($this->customer->get_last_name(), $wcCustomer->get_last_name());
$this->assertEquals($this->customer->get_billing_phone(), $wcCustomer->get_billing_phone());
$this->assertEquals($this->customer->get_email(), $wcCustomer->get_email());
}
public function test_load_wc_customer_by_not_valid_id()
{
$builder = new WC_Retailcrm_WC_Customer_Builder();
$builder->loadExternalId(null);
$wcCustomer = $builder->getResult();
$this->assertInstanceOf('\WC_Customer', $wcCustomer);
$this->assertEquals(null, $wcCustomer->get_id());
$this->assertEquals(null, $wcCustomer->get_first_name());
$this->assertEquals(null, $wcCustomer->get_last_name());
$this->assertEquals(null, $wcCustomer->get_billing_phone());
$this->assertEquals(null, $wcCustomer->get_email());
}
/**
* @return array
*/
public function customerData() public function customerData()
{ {
return array( return array(
@ -121,8 +266,12 @@ class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helpe
'personalDiscount' => 0, 'personalDiscount' => 0,
'cumulativeDiscount' => 0, 'cumulativeDiscount' => 0,
'address' => array( 'address' => array(
'id' => 3132, 'id' => 3132,
'text' => 'ул. Пушкина дом Колотушкина', 'text' => 'street_test',
'region' => 'region_test',
'index' => '112233',
'country' => 'country_test',
'city' => 'city_test'
), ),
'segments' => array(), 'segments' => array(),
'firstName' => 'tester001', 'firstName' => 'tester001',
@ -135,3 +284,4 @@ class WC_Retailcrm_WC_Customer_Builder_Test extends WC_Retailcrm_Test_Case_Helpe
); );
} }
} }

View File

@ -0,0 +1,82 @@
<?php
namespace datasets;
class DataBaseRetailCrm
{
public static function getResponseStatuses()
{
return array(
'success' => true,
'statuses' => array(
array(
'name' => 'status1',
'code' => 'status1',
'active' => true
),
array(
'name' => 'status2',
'code' => 'status2',
'active' => false
)
)
);
}
public static function getResponsePaymentTypes()
{
return array(
'success' => true,
'paymentTypes' => array(
array(
'name' => 'payment1',
'code' => 'payment1',
'active' => true
),
array(
'name' => 'payment2',
'code' => 'payment2',
'active' => false
)
)
);
}
public static function getResponseDeliveryTypes()
{
return array(
'success' => true,
'deliveryTypes' => array(
array(
'name' => 'delivery1',
'code' => 'delivery1',
'active' => true
),
array(
'name' => 'delivery2',
'code' => 'delivery2',
'active' => false
)
)
);
}
public static function getResponseOrderMethods()
{
return array(
'success' => true,
'orderMethods' => array(
array(
'name' => 'orderMethod1',
'code' => 'orderMethod1',
'active' => true
),
array(
'name' => 'orderMethod2',
'code' => 'orderMethod2',
'active' => false
)
)
);
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace datasets;
class DataCustomersRetailCrm
{
public static function getCustomerAddress()
{
return array(
'success' => true,
'addresses' => array (
'id' => 3503,
'index' => 144566,
'countryIso' => 'ES',
'region' => 'Region',
'city' => 'City',
'text' => 'street Test 777',
)
);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
<?php
namespace datasets;
class DataInventoriesRetailCrm {
public static function getResponseData()
{
return array(
'success' => true,
'pagination' => array(
'limit' => 250,
'totalCount' => 1,
'currentPage' => 1,
'totalPageCount' => 1
),
'offers' => array(
array(
'id' => 1,
'xmlId' => 'xmlId',
'quantity' => 10
)
)
);
}
}

View File

@ -12,14 +12,15 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
{ {
$options = array( $options = array(
'api_url' => 'https://example.retailcrm.ru', 'api_url' => 'https://example.retailcrm.ru',
'api_key' => 'dhsHJGYdjkHHJKJSGjhasjhgajsgJGHsg', 'api_key' => 'test_key',
'api_version' => 'v5', 'corporate_enabled' => 'yes',
'online_assistant' => 'code',
'p_draft' => 'no', 'p_draft' => 'no',
'p_pending' => 'no', 'p_pending' => 'no',
'p_private' => 'no', 'p_private' => 'no',
'p_publish' => 'no', 'p_publish' => 'no',
'send_payment_amount' => 'yes', 'catalog_options' => 'no',
'order_methods' => '', 'order_methods' => array(0 => 'phone'),
'flat_rate_shipping' => 'delivery', 'flat_rate_shipping' => 'delivery',
'free_shipping' => 'delivery2', 'free_shipping' => 'delivery2',
'local_pickup' => 'delivery3', 'local_pickup' => 'delivery3',
@ -35,11 +36,23 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
'cancelled' => 'status5', 'cancelled' => 'status5',
'refunded' => 'status6', 'refunded' => 'status6',
'failed' => 'status7', 'failed' => 'status7',
'sync' => 'no', 'sync' => 'yes',
'ua' => 'yes', 'ua' => 'yes',
'ua_code' => 'UA-XXXXXXX-XX', 'ua_code' => 'UA-XXXXXXX-XX',
'ua_custom' => '1', 'ua_custom' => '1',
'upload-button' => '' 'daemon_collector' => 'yes',
'upload-button' => '',
'whatsapp_active' => 'yes',
'whatsapp_location_icon' => 'yes',
'whatsapp_number' => '+79184567234',
'icml' => 'yes',
'single_order' => '123',
'history' => 'yes',
'deactivate_update_order' => 'no',
'bind_by_sku' => 'no',
'update_number' => 'yes',
'debug_mode' => 'yes',
'debug-info' => ''
); );
update_option(WC_Retailcrm_Base::$option_key, $options); update_option(WC_Retailcrm_Base::$option_key, $options);
@ -91,4 +104,19 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
{ {
return get_option(WC_Retailcrm_Base::$option_key); return get_option(WC_Retailcrm_Base::$option_key);
} }
/**
* @param $mock
* @param $method
* @param $response
*
* @return void
*/
protected function setMockResponse($mock, $method, $response)
{
$mock->expects($this->any())
->method($method)
->willReturn($response);
}
} }

View File

@ -11,6 +11,21 @@
class WC_Retailcrm_Customer_Switcher_Result_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Customer_Switcher_Result_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $customer;
public function setUp()
{
$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_password('password');
$this->customer->set_billing_phone('89000000000');
$this->customer->set_date_created(date('Y-m-d H:i:s'));
$this->customer->save();
}
/** /**
* @expectedException \InvalidArgumentException * @expectedException \InvalidArgumentException
*/ */
@ -37,7 +52,8 @@ class WC_Retailcrm_Customer_Switcher_Result_Test extends WC_Retailcrm_Test_Case_
public function test_valid() public function test_valid()
{ {
$result = new WC_Retailcrm_Customer_Switcher_Result(new WC_Customer(), new WC_Order()); $result = new WC_Retailcrm_Customer_Switcher_Result($this->customer, new WC_Order());
$this->assertInstanceOf('\WC_Customer', $result->getWcCustomer()); $this->assertInstanceOf('\WC_Customer', $result->getWcCustomer());
$this->assertInstanceOf('\WC_Order', $result->getWcOrder()); $this->assertInstanceOf('\WC_Order', $result->getWcOrder());
} }
@ -45,7 +61,18 @@ class WC_Retailcrm_Customer_Switcher_Result_Test extends WC_Retailcrm_Test_Case_
public function test_valid_no_customer() public function test_valid_no_customer()
{ {
$result = new WC_Retailcrm_Customer_Switcher_Result(null, new WC_Order()); $result = new WC_Retailcrm_Customer_Switcher_Result(null, new WC_Order());
$this->assertEmpty($result->getWcCustomer())
; $this->assertInstanceOf('\WC_Order', $result->getWcOrder()); $this->assertEmpty($result->getWcCustomer());
$this->assertInstanceOf('\WC_Order', $result->getWcOrder());
}
public function test_save()
{
$switcher = new WC_Retailcrm_Customer_Switcher_Result($this->customer, new WC_Order());
$switcher->save();
$this->assertInstanceOf('\WC_Customer', $switcher->getWcCustomer());
} }
} }

View File

@ -14,6 +14,7 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
public function test_feasible() public function test_feasible()
{ {
$state = new WC_Retailcrm_Customer_Switcher_State(); $state = new WC_Retailcrm_Customer_Switcher_State();
$this->assertFalse($state->feasible()); $this->assertFalse($state->feasible());
$state->setNewCustomer(array()) $state->setNewCustomer(array())
@ -35,7 +36,7 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
$state->setNewCustomer(array()) $state->setNewCustomer(array())
->setNewContact(array()) ->setNewContact(array())
->setNewCompany(array('name' => 'test')); ->setNewCompany(array('name' => 'test', 'address' => 'address_test'));
$this->assertTrue($state->feasible()); $this->assertTrue($state->feasible());
$state->setNewCustomer(array()) $state->setNewCustomer(array())
@ -50,6 +51,7 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
public function test_validate_empty() public function test_validate_empty()
{ {
$state = new WC_Retailcrm_Customer_Switcher_State(); $state = new WC_Retailcrm_Customer_Switcher_State();
$state->validate(); $state->validate();
} }
@ -59,8 +61,8 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
public function test_validate_order() public function test_validate_order()
{ {
$state = new WC_Retailcrm_Customer_Switcher_State(); $state = new WC_Retailcrm_Customer_Switcher_State();
$state->setWcOrder(new WC_Order())
->validate(); $state->setWcOrder(new WC_Order())->validate();
} }
/** /**
@ -69,6 +71,7 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
public function test_validate_customer_and_contact_set() public function test_validate_customer_and_contact_set()
{ {
$state = new WC_Retailcrm_Customer_Switcher_State(); $state = new WC_Retailcrm_Customer_Switcher_State();
$state->setWcOrder(new WC_Order()) $state->setWcOrder(new WC_Order())
->setNewCustomer(array('id' => 1)) ->setNewCustomer(array('id' => 1))
->setNewContact(array('id' => 1)) ->setNewContact(array('id' => 1))
@ -76,13 +79,15 @@ class WC_Retailcrm_Customer_Switcher_State_Test extends WC_Retailcrm_Test_Case_H
} }
/** /**
* @@doesNotPerformAssertions * @doesNotPerformAssertions
*/ */
public function test_validate_ok() public function test_validate_ok()
{ {
$state = new WC_Retailcrm_Customer_Switcher_State(); $state = new WC_Retailcrm_Customer_Switcher_State();
$state->setWcOrder(new WC_Order()) $state->setWcOrder(new WC_Order())
->setNewCustomer(array('id' => 1)) ->setNewCustomer(array('id' => 1))
->validate(); ->validate();
} }
} }

View File

@ -35,4 +35,16 @@ class WC_Retailcrm_Order_Item_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertArrayHasKey('offer', $data); $this->assertArrayHasKey('offer', $data);
} }
} }
public function test_bind_by_sku()
{
$order_item = new WC_Retailcrm_Order_Item(['bind_by_sku' => 'yes']);
foreach ($this->order->get_items() as $item) {
$data = $order_item->build($item)->get_data();
$this->assertArrayHasKey('offer', $data);
$this->assertArrayHasKey('xmlId', $data['offer']);
}
}
} }

View File

@ -44,6 +44,62 @@ class WC_Retailcrm_Order_Payment_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertArrayHasKey('order', $data); $this->assertArrayHasKey('order', $data);
} }
/**
* @param mixed $externalId
*
* @dataProvider dataProvider
*/
public function test_build_payment_type_not_exist($externalId)
{
$order_payment = new WC_Retailcrm_Order_Payment('test');
$data = $order_payment->build($this->order, $externalId)->get_data();
$this->assertEmpty($data);
}
/**
* @param mixed $externalId
*
* @dataProvider dataProvider
*/
public function test_not_new_payment($externalId)
{
$settings = $this->getOptions();
$order_payment = new WC_Retailcrm_Order_Payment($settings);
$order_payment->is_new = false;
$data = $order_payment->build($this->order, $externalId)->get_data();
$this->assertEmpty($data);
}
/**
* @param mixed $externalId
*
* @dataProvider dataProvider
*/
public function test_order_paid($externalId)
{
$settings = $this->getOptions();
$order_payment = new WC_Retailcrm_Order_Payment($settings);
$this->order->update_status('completed');
$data = $order_payment->build($this->order, $externalId)->get_data();
$this->assertNotEmpty($data);
if (!empty($externalId)) {
$this->assertArrayHasKey('externalId', $data);
}
$this->assertArrayHasKey('type', $data);
$this->assertArrayHasKey('order', $data);
}
/** /**
* @param mixed $externalId * @param mixed $externalId
* *

View File

@ -0,0 +1,60 @@
<?php
/**
* PHP version 5.3
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Order_Test extends WC_Retailcrm_Test_Case_Helper {
/** @var WC_Order */
protected $order;
public function setUp()
{
parent::setUp();
$this->order = WC_Helper_Order::create_order();
}
public function test_reset_data()
{
$buildOrder = new WC_Retailcrm_Order($this->getOptions());
$data = $buildOrder->build($this->order)->get_data();
$this->assertNotEmpty($data);
$buildOrder->reset_data();
$this->assertEmpty(array_filter($buildOrder->get_data()));
}
public function test_empty_shipping_data()
{
$buildOrder = new WC_Retailcrm_Order($this->getOptions());
$data = $buildOrder->build($this->order)->get_data();
$this->assertNotEmpty($data);
$this->assertArrayHasKey('firstName', $data);
$this->assertArrayHasKey('lastName', $data);
$this->assertEquals($this->order->get_billing_first_name(), $data['firstName']);
$this->assertEquals($this->order->get_billing_last_name(), $data['lastName']);
}
public function test_empty_country_iso()
{
$buildOrder = new WC_Retailcrm_Order($this->getOptions());
$this->order->set_shipping_country('');
$data = $buildOrder->build($this->order)->get_data();
$this->assertNotEmpty($data);
$this->assertArrayHasKey('countryIso', $data);
$this->assertNotEquals('', $data['countryIso']);
}
}

View File

@ -1,5 +1,7 @@
<?php <?php
use datasets\DataBaseRetailCrm;
class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $apiMock; protected $apiMock;
@ -7,20 +9,22 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
protected $responseMockDeliveryTypes; protected $responseMockDeliveryTypes;
protected $responseMockPaymentTypes; protected $responseMockPaymentTypes;
protected $responseMockStatuses; protected $responseMockStatuses;
protected $dataOptions;
private $unit; private $baseRetailcrm;
public function setUp() public function setUp()
{ {
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(
'orderMethodsList', array(
'deliveryTypesList', 'orderMethodsList',
'paymentTypesList', 'deliveryTypesList',
'statusesList' 'paymentTypesList',
)) 'statusesList'
->getMock(); )
)
->getMock();
$this->setMockOrderMethods(); $this->setMockOrderMethods();
$this->setMockDeliveryTypes(); $this->setMockDeliveryTypes();
@ -30,25 +34,25 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
$_GET['page'] = 'wc-settings'; $_GET['page'] = 'wc-settings';
$_GET['tab'] = 'integration'; $_GET['tab'] = 'integration';
$this->setOptions('v5'); $this->dataOptions = $this->setOptions();
$this->unit = new \WC_Retailcrm_Base($this->apiMock); $this->baseRetailcrm = new \WC_Retailcrm_Base($this->apiMock);
} }
public function test_retailcrm_form_fields() public function test_retailcrm_form_fields()
{ {
$this->assertInternalType('array', $this->unit->form_fields); $this->assertInternalType('array', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('api_url', $this->unit->form_fields); $this->assertArrayHasKey('api_url', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('api_key', $this->unit->form_fields); $this->assertArrayHasKey('api_key', $this->baseRetailcrm->form_fields);
foreach (get_post_statuses() as $key => $status) { foreach (get_post_statuses() as $key => $status) {
$this->assertArrayHasKey('p_' . $key, $this->unit->form_fields); $this->assertArrayHasKey('p_' . $key, $this->baseRetailcrm->form_fields);
} }
$this->assertArrayHasKey('order_methods', $this->unit->form_fields); $this->assertArrayHasKey('order_methods', $this->baseRetailcrm->form_fields);
foreach (get_wc_shipping_methods() as $code => $value) { foreach (get_wc_shipping_methods() as $code => $value) {
if (isset($value['enabled']) && $value['enabled'] == 'yes') { if (isset($value['enabled']) && $value['enabled'] == 'yes') {
$this->assertArrayHasKey($code, $this->unit->form_fields); $this->assertArrayHasKey($code, $this->baseRetailcrm->form_fields);
} }
} }
@ -56,165 +60,276 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
foreach ($wc_payment->get_available_payment_gateways() as $payment) { foreach ($wc_payment->get_available_payment_gateways() as $payment) {
if (isset($payment->enabled) && $payment->enabled == 'yes') { if (isset($payment->enabled) && $payment->enabled == 'yes') {
$this->assertArrayHasKey($payment->id, $this->unit->form_fields); $this->assertArrayHasKey($payment->id, $this->baseRetailcrm->form_fields);
} }
} }
foreach (wc_get_order_statuses() as $idx => $name ) { foreach (wc_get_order_statuses() as $idx => $name) {
$uid = str_replace('wc-', '', $idx); $uid = str_replace('wc-', '', $idx);
$this->assertArrayHasKey($uid, $this->unit->form_fields); $this->assertArrayHasKey($uid, $this->baseRetailcrm->form_fields);
}
$this->assertArrayHasKey('corporate_enabled', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('online_assistant', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('catalog_options', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('order_methods', $this->baseRetailcrm->form_fields);
$this->assertInternalType('array', $this->baseRetailcrm->form_fields['order_methods']);
$this->assertArrayHasKey('whatsapp_active', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('whatsapp_location_icon', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('whatsapp_number', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('icml', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('single_order', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('history', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('deactivate_update_order', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('bind_by_sku', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('update_number', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('debug_mode', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('debug-info', $this->baseRetailcrm->form_fields);
}
public function test_retailcrm_form_fields_value()
{
foreach ($this->getOptions() as $key => $value) {
if (is_array($value) === false) {
$this->assertEquals($this->dataOptions[$key], $value);
} else {
$this->assertEquals($this->dataOptions[$key][0], $value[0]);
}
} }
} }
private function getResponseOrderMethods() public function test_initialize_online_assistant()
{ {
return array( ob_start();
'success' => true, $this->baseRetailcrm->initialize_online_assistant($this->dataOptions);
'orderMethods' => array(
array( $this->assertEquals($this->dataOptions['online_assistant'], ob_get_contents());
'name' => 'orderMethod1', ob_end_clean();
'code' => 'orderMethod1',
'active' => true
),
array(
'name' => 'orderMethod2',
'code' => 'orderMethod2',
'active' => false
)
)
);
} }
private function getResponseDeliveryTypes() public function test_option_cron_enabled()
{ {
return array( $this->baseRetailcrm->api_sanitized($this->getOptions());
'success' => true,
'deliveryTypes' => array( $history = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_history'));
array( $icml = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_icml'));
'name' => 'delivery1', $inventories = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_inventories'));
'code' => 'delivery1',
'active' => true $this->assertInternalType('string', $history);
), $this->assertInternalType('string', $icml);
array( $this->assertInternalType('string', $inventories);
'name' => 'delivery2',
'code' => 'delivery2',
'active' => true
)
)
);
} }
private function getResponsePaymentTypes() public function test_option_cron_disabled()
{ {
return array( $settings = $this->baseRetailcrm->api_sanitized(
'success' => true, array(
'paymentTypes' => array( 'api_url' => 'https://example.retailcrm.ru',
array( 'api_key' => 'test_key',
'name' => 'payment1', 'corporate_enabled' => 'yes',
'code' => 'payment1', 'sync' => 'no',
'active' => true 'icml' => 'no',
), 'history' => 'no',
array(
'name' => 'payment2',
'code' => 'payment2',
'active' => true
)
) )
); );
$history = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_history'));
$icml = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_icml'));
$inventories = date('H:i:s d-m-Y', wp_next_scheduled('retailcrm_inventories'));
$this->assertEquals('00:00:00 01-01-1970', $history);
$this->assertEquals('00:00:00 01-01-1970', $icml);
$this->assertEquals('00:00:00 01-01-1970', $inventories);
$this->assertInternalType('array', $settings);
$this->assertArrayHasKey('api_url', $settings);
$this->assertEquals('https://example.retailcrm.ru', $settings['api_url']);
$this->assertArrayHasKey('api_key', $settings);
$this->assertEquals('test_key', $settings['api_key']);
$this->assertArrayHasKey('corporate_enabled', $settings);
$this->assertEquals('yes', $settings['corporate_enabled']);
$this->assertArrayHasKey('sync', $settings);
$this->assertEquals('no', $settings['sync']);
$this->assertArrayHasKey('icml', $settings);
$this->assertEquals('no', $settings['icml']);
$this->assertArrayHasKey('history', $settings);
$this->assertEquals('no', $settings['history']);
} }
private function getResponseStatuses()
public function test_get_cron_info()
{ {
return array( ob_start();
'success' => true, $this->baseRetailcrm->get_cron_info();
'statuses' => array(
array( $cronInfo = $this->getJsonData(ob_get_contents());
'name' => 'status1',
'code' => 'status1', $this->assertInternalType('array', $cronInfo);
'active' => true $this->assertArrayHasKey('history', $cronInfo);
), $this->assertArrayHasKey('icml', $cronInfo);
array( $this->assertArrayHasKey('inventories', $cronInfo);
'name' => 'status2', $this->assertInternalType('string', $cronInfo['history']);
'code' => 'status2', $this->assertInternalType('string', $cronInfo['icml']);
'active' => true $this->assertInternalType('string', $cronInfo['inventories']);
) $this->assertNotEquals('This option is disabled', $cronInfo['history']);
) $this->assertNotEquals('This option is disabled', $cronInfo['icml']);
$this->assertNotEquals('This option is disabled', $cronInfo['inventories']);
ob_end_clean();
}
public function test_get_cron_info_off()
{
$this->baseRetailcrm->settings = array('sync' => 'no', 'icml' => 'no', 'history' => 'no');
ob_start();
$this->baseRetailcrm->get_cron_info();
$cronInfo = $this->getJsonData(ob_get_contents());
$this->assertInternalType('array', $cronInfo);
$this->assertArrayHasKey('history', $cronInfo);
$this->assertArrayHasKey('icml', $cronInfo);
$this->assertArrayHasKey('inventories', $cronInfo);
$this->assertInternalType('string', $cronInfo['history']);
$this->assertInternalType('string', $cronInfo['icml']);
$this->assertInternalType('string', $cronInfo['inventories']);
$this->assertEquals('This option is disabled', $cronInfo['history']);
$this->assertEquals('This option is disabled', $cronInfo['icml']);
$this->assertEquals('This option is disabled', $cronInfo['inventories']);
ob_end_clean();
}
public function test_count_upload_data()
{
ob_start();
$this->baseRetailcrm->count_upload_data();
$uploadInfo = $this->getJsonData(ob_get_contents());
$this->assertInternalType('array', $uploadInfo);
$this->assertArrayHasKey('count_orders', $uploadInfo);
$this->assertArrayHasKey('count_users', $uploadInfo);
$this->assertInternalType('integer', $uploadInfo['count_orders']);
$this->assertInternalType('integer', $uploadInfo['count_users']);
ob_end_clean();
}
public function test_initialize_whatsapp()
{
ob_start();
$this->baseRetailcrm->initialize_whatsapp();
$js = ob_get_contents();
$this->assertNotEquals('', $js);
$this->assertContains('79184567234', $js);
ob_end_clean();
}
public function test_initialize_whatsapp_off()
{
$this->baseRetailcrm->settings = array(
'whatsapp_active' => 'no',
'whatsapp_location_icon' => 'no',
'whatsapp_number' => '',
); );
ob_start();
$this->baseRetailcrm->initialize_whatsapp();
$this->assertEquals('', ob_get_contents());
ob_end_clean();
}
public function test_initialize_daemon_collector_off()
{
$this->baseRetailcrm->settings = array('daemon_collector' => 'no', 'daemon_collector_key' => '');
ob_start();
$this->baseRetailcrm->initialize_daemon_collector();
$this->assertEquals('', ob_get_contents());
ob_end_clean();
}
public function test_initialize_analytics()
{
ob_start();
$this->baseRetailcrm->initialize_analytics();
$js = ob_get_contents();
$this->assertNotEquals('', $js);
$this->assertContains('UA-XXXXXXX-XX', $js);
ob_end_clean();
}
public function test_initialize_analytics_off()
{
$this->baseRetailcrm->settings = array('ua' => '', 'ua_code' => '', 'ua_custom' => '');
ob_start();
$this->baseRetailcrm->initialize_analytics();
$this->assertEquals('', ob_get_contents());
ob_end_clean();
}
private function getJsonData($text)
{
preg_match('/{.*}/', $text, $matches);
return json_decode($matches[0], true);
} }
private function setMockOrderMethods() private function setMockOrderMethods()
{ {
$this->responseMockOrderMethods = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMockOrderMethods = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
)) $this->setMockResponse($this->responseMockOrderMethods, 'isSuccessful', true);
->getMock();
$this->responseMockOrderMethods->expects($this->any()) $this->responseMockOrderMethods->setResponse(DataBaseRetailCrm::getResponseOrderMethods());
->method('isSuccessful') $this->setMockResponse($this->apiMock, 'orderMethodsList', $this->responseMockOrderMethods);
->willReturn(true);
$this->responseMockOrderMethods->setResponse($this->getResponseOrderMethods());
$this->apiMock->expects($this->any())
->method('orderMethodsList')
->willReturn($this->responseMockOrderMethods);
} }
private function setMockDeliveryTypes() private function setMockDeliveryTypes()
{ {
$this->responseMockDeliveryTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMockDeliveryTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
)) $this->setMockResponse($this->responseMockDeliveryTypes, 'isSuccessful', true);
->getMock();
$this->responseMockDeliveryTypes->expects($this->any()) $this->responseMockDeliveryTypes->setResponse(DataBaseRetailCrm::getResponseDeliveryTypes());
->method('isSuccessful') $this->setMockResponse($this->apiMock, 'deliveryTypesList', $this->responseMockDeliveryTypes);
->willReturn(true);
$this->responseMockDeliveryTypes->setResponse($this->getResponseDeliveryTypes());
$this->apiMock->expects($this->any())
->method('deliveryTypesList')
->willReturn($this->responseMockDeliveryTypes);
} }
private function setMockPaymentTypes() private function setMockPaymentTypes()
{ {
$this->responseMockPaymentTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMockPaymentTypes = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
)) $this->setMockResponse($this->responseMockPaymentTypes, 'isSuccessful', true);
->getMock();
$this->responseMockPaymentTypes->expects($this->any()) $this->responseMockPaymentTypes->setResponse(DataBaseRetailCrm::getResponsePaymentTypes());
->method('isSuccessful') $this->setMockResponse($this->apiMock, 'paymentTypesList', $this->responseMockPaymentTypes);
->willReturn(true);
$this->responseMockPaymentTypes->setResponse($this->getResponsePaymentTypes());
$this->apiMock->expects($this->any())
->method('paymentTypesList')
->willReturn($this->responseMockPaymentTypes);
} }
private function setMockStatuses() private function setMockStatuses()
{ {
$this->responseMockStatuses = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMockStatuses = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
)) $this->setMockResponse($this->responseMockStatuses, 'isSuccessful', true);
->getMock();
$this->responseMockStatuses->expects($this->any()) $this->responseMockStatuses->setResponse(DataBaseRetailCrm::getResponseStatuses());
->method('isSuccessful') $this->setMockResponse($this->apiMock, 'statusesList', $this->responseMockStatuses);
->willReturn(true);
$this->responseMockStatuses->setResponse($this->getResponseStatuses());
$this->apiMock->expects($this->any())
->method('statusesList')
->willReturn($this->responseMockStatuses);
} }
} }

View File

@ -1,5 +1,7 @@
<?php <?php
use datasets\DataCustomersRetailCrm;
class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $apiMock; protected $apiMock;
@ -8,32 +10,43 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
public function setUp() public function setUp()
{ {
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response') $this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array(
'isSuccessful' 'isSuccessful',
)) 'offsetExists'
->getMock(); ))
->getMock();
$this->responseMock->setResponse(array('id' => 1));
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array(
'ordersGet', 'ordersGet',
'ordersCreate', 'ordersCreate',
'ordersEdit', 'ordersEdit',
'customersGet', 'customersGet',
'customersCreate', 'customersCreate',
'customersEdit' 'customersEdit',
)) 'getCorporateEnabled',
->getMock(); 'customersCorporateCreate',
'customersCorporateAddressesCreate',
'customersCorporateCompaniesCreate',
'getSingleSiteForKey',
'customersCorporateAddresses'
))
->getMock();
$this->responseMock->expects($this->any()) $this->setMockResponse($this->responseMock, 'isSuccessful', true);
->method('isSuccessful') $this->setMockResponse($this->responseMock, 'offsetExists', true);
->willReturn(true); $this->setMockResponse($this->apiMock, 'getCorporateEnabled', true);
$this->setMockResponse($this->apiMock, 'getSingleSiteForKey', 'test');
$this->apiMock->expects($this->any()) $this->setMockResponse($this->apiMock, 'customersCreate', $this->responseMock);
->method('customersCreate') $this->setMockResponse($this->apiMock, 'customersCorporateCreate', $this->responseMock);
->willReturn($this->responseMock); $this->setMockResponse($this->apiMock, 'customersCorporateAddressesCreate', $this->responseMock);
$this->setMockResponse($this->apiMock, 'customersCorporateCompaniesCreate', $this->responseMock);
$this->setMockResponse($this->apiMock, 'customersCorporateCreate', true);
$this->customer = new WC_Customer(); $this->customer = new WC_Customer();
$this->customer->set_first_name('Tester'); $this->customer->set_first_name('Tester');
@ -42,69 +55,89 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
$this->customer->set_billing_email($this->customer->get_email()); $this->customer->set_billing_email($this->customer->get_email());
$this->customer->set_password('password'); $this->customer->set_password('password');
$this->customer->set_billing_phone('89000000000'); $this->customer->set_billing_phone('89000000000');
$this->customer->set_billing_company('test_company');
$this->customer->set_billing_state('test_state');
$this->customer->set_billing_postcode('123456');
$this->customer->set_billing_city('test_city');
$this->customer->set_billing_address_1('test_address_line');
$this->customer->set_date_created(date('Y-m-d H:i:s')); $this->customer->set_date_created(date('Y-m-d H:i:s'));
$this->customer->save(); $this->customer->save();
} }
/** /**
* @param retailcrm * @param retailcrm
*
* @dataProvider dataProviderApiClient * @dataProvider dataProviderApiClient
*/ */
public function test_wc_customer_get($retailcrm) public function test_wc_customer_get($retailcrm)
{ {
$wc_customer = new WC_Customer($this->customer->get_id()); $wc_customer = new WC_Customer($this->customer->get_id());
$retailcrm_customer = $this->getRetailcrmCustomer($retailcrm); $retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$this->assertEquals($wc_customer, $retailcrm_customer->wcCustomerGet($this->customer->get_id()));
}
$this->assertEquals($wc_customer, $retailcrmCustomer->wcCustomerGet($this->customer->get_id()));
}
/** /**
* @param $retailcrm * @param $retailcrm
*
* @dataProvider dataProviderApiClient * @dataProvider dataProviderApiClient
*/ */
public function test_create_customer($retailcrm) public function test_create_customer($retailcrm)
{ {
$retailcrm_customer = $this->getRetailcrmCustomer($retailcrm); $retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$id = $retailcrm_customer->createCustomer($this->customer->get_id()); $id = $retailcrmCustomer->createCustomer($this->customer->get_id());
$customer_send = $retailcrm_customer->getCustomer(); $customer = $retailcrmCustomer->getCustomer();
if ($retailcrm) { if ($retailcrm) {
$this->assertArrayHasKey('firstName', $customer_send); $this->assertArrayHasKey('firstName', $customer);
$this->assertArrayHasKey('createdAt', $customer_send); $this->assertArrayHasKey('createdAt', $customer);
$this->assertArrayHasKey('email', $customer_send); $this->assertArrayHasKey('email', $customer);
$this->assertNotEmpty($customer_send['externalId']); $this->assertNotEmpty($customer['externalId']);
$this->assertNotEmpty($customer_send['createdAt']); $this->assertNotEmpty($customer['createdAt']);
$this->assertNotEmpty($customer_send['firstName']); $this->assertNotEmpty($customer['firstName']);
$this->assertNotEmpty($customer_send['email']); $this->assertNotEmpty($customer['email']);
$this->assertEquals($customer['firstName'], $this->customer->get_first_name());
$this->assertEquals($customer['email'], $this->customer->get_email());
} else { } else {
$this->assertEquals(null, $id); $this->assertEquals(null, $id);
$this->assertEquals(array(), $customer_send); $this->assertEquals(array(), $customer);
} }
} }
public function test_create_customer_empty_data()
{
$retailcrmCustomer = $this->getRetailcrmCustomer($this->apiMock);
$id = $retailcrmCustomer->createCustomer(null);
$customer = $retailcrmCustomer->getCustomer();
$this->assertEquals(null, $id);
$this->assertEquals(array(), $customer);
}
/** /**
* @param $retailcrm * @param $retailcrm
*
* @dataProvider dataProviderApiClient * @dataProvider dataProviderApiClient
*/ */
public function test_update_customer($retailcrm) public function test_update_customer($retailcrm)
{ {
$retailcrm_customer = $this->getRetailcrmCustomer($retailcrm); $retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$customer = $retailcrm_customer->updateCustomer($this->customer->get_id()); $wcCustomer = $retailcrmCustomer->updateCustomer($this->customer->get_id());
$customer_send = $retailcrm_customer->getCustomer(); $customer = $retailcrmCustomer->getCustomer();
if ($retailcrm) { if ($retailcrm) {
$this->assertArrayHasKey('externalId', $customer_send); $this->assertInstanceOf('WC_Customer', $wcCustomer);
$this->assertArrayHasKey('firstName', $customer_send); $this->assertArrayHasKey('externalId', $customer);
$this->assertArrayHasKey('createdAt', $customer_send); $this->assertArrayHasKey('firstName', $customer);
$this->assertArrayHasKey('email', $customer_send); $this->assertArrayHasKey('createdAt', $customer);
$this->assertNotEmpty($customer_send['externalId']); $this->assertArrayHasKey('email', $customer);
$this->assertNotEmpty($customer_send['createdAt']); $this->assertNotEmpty($customer['externalId']);
$this->assertNotEmpty($customer_send['firstName']); $this->assertNotEmpty($customer['createdAt']);
$this->assertNotEmpty($customer_send['email']); $this->assertNotEmpty($customer['firstName']);
$this->assertInstanceOf('WC_Customer', $customer); $this->assertNotEmpty($customer['email']);
} else { } else {
$this->assertEquals(null, $customer); $this->assertEquals(null, $wcCustomer);
$this->assertEquals(array(), $customer_send); $this->assertEquals(array(), $customer);
} }
} }
@ -112,17 +145,101 @@ class WC_Retailcrm_Customers_Test extends WC_Retailcrm_Test_Case_Helper
* @param $retailcrm * @param $retailcrm
* *
* @dataProvider dataProviderApiClient * @dataProvider dataProviderApiClient
* @throws \Exception
*/ */
public function test_create_customer_empty_response($retailcrm) public function test_update_customer_by_id($retailcrm)
{ {
$this->responseMock = null; $retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$this->apiMock = null; $wcCustomer = $retailcrmCustomer->updateCustomerById($this->customer->get_id(), '12345');
$customer = $retailcrmCustomer->getCustomer();
$retailcrm_customer = $this->getRetailcrmCustomer($retailcrm); if ($retailcrm) {
$id = $retailcrm_customer->createCustomer($this->customer->get_id()); $this->assertInstanceOf('WC_Customer', $wcCustomer);
$this->assertArrayHasKey('externalId', $customer);
$this->assertArrayHasKey('firstName', $customer);
$this->assertArrayHasKey('createdAt', $customer);
$this->assertArrayHasKey('email', $customer);
$this->assertNotEmpty($customer['externalId']);
$this->assertNotEmpty($customer['createdAt']);
$this->assertNotEmpty($customer['firstName']);
$this->assertNotEmpty($customer['email']);
} else {
$this->assertEquals(null, $wcCustomer);
$this->assertEquals(array(), $customer);
}
}
/**
* @param $retailcrm
*
* @dataProvider dataProviderApiClient
*/
public function test_is_corparate_enabled($retailcrm)
{
$retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$isCorporate = $retailcrmCustomer->isCorporateEnabled();
if ($retailcrm) {
$this->assertEquals(true, $isCorporate);
} else {
$this->assertEquals(false, $isCorporate);
}
}
/**
* @param $retailcrm
*
* @dataProvider dataProviderApiClient
*/
public function test_create_customer_corporate($retailcrm)
{
$retailcrmCustomer = $this->getRetailcrmCustomer($retailcrm);
$id = $retailcrmCustomer->createCorporateCustomerForOrder(777, $this->customer->get_id(), new WC_Order());
$customer = $retailcrmCustomer->getCorporateCustomer();
if ($retailcrm) {
$this->assertArrayHasKey('customerContacts', $customer);
foreach ($customer['customerContacts'] as $customerCorporate) {
$this->assertArrayHasKey('isMain', $customerCorporate);
$this->assertArrayHasKey('customer', $customerCorporate);
$this->assertEquals($customerCorporate['isMain'], true);
$this->assertEquals($customerCorporate['customer']['id'], 777);
}
} else {
$this->assertEquals(null, $id);
$this->assertEquals(array(), $customer);
}
}
public function test_create_customer_corporate_empty_data()
{
$retailcrmCustomer = $this->getRetailcrmCustomer($this->apiMock);
$id = $retailcrmCustomer->createCorporateCustomerForOrder(777, null, new WC_Order());
$customer = $retailcrmCustomer->getCorporateCustomer();
$this->assertEquals(null, $id); $this->assertEquals(null, $id);
$this->assertEquals(array(), $customer);
}
public function test_fill_corporate_address()
{
$retailcrmCustomer = $this->getRetailcrmCustomer($this->apiMock);
// Mock response for get customer address
$responseCustomerAddress = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array('isSuccessful'))
->getMock();
$this->setMockResponse($responseCustomerAddress, 'isSuccessful', true);
$responseCustomerAddress->setResponse(DataCustomersRetailCrm::getCustomerAddress());
//Set responseCustomerAddress mock for apiMock
$this->setMockResponse($this->apiMock, 'customersCorporateAddresses', $responseCustomerAddress);
$addressFound = $retailcrmCustomer->fillCorporateAddress($this->customer->get_id(), $this->customer);
$this->assertEquals(true, $addressFound);
} }
public function dataProviderApiClient() public function dataProviderApiClient()

View File

@ -27,12 +27,15 @@ class WC_Retailcrm_Google_Analytics_Test extends WC_Retailcrm_Test_Case_Helper
/** /**
* @param $checkout * @param $checkout
*
* @dataProvider dataProvider * @dataProvider dataProvider
*/ */
public function test_send_analytics($checkout) public function test_send_analytics($checkout)
{ {
if ($checkout) { if ($checkout === true) {
$_GET['key'] = $this->orderKey; $_GET['key'] = $this->orderKey;
} elseif (is_null($checkout)) {
$_GET['key'] = '';
} }
$js = $this->ga->send_analytics(); $js = $this->ga->send_analytics();
@ -53,6 +56,9 @@ class WC_Retailcrm_Google_Analytics_Test extends WC_Retailcrm_Test_Case_Helper
array( array(
'checkout' => false 'checkout' => false
), ),
array(
'checkout' => null
),
array( array(
'checkout' => true 'checkout' => true
) )

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,25 @@
<?php <?php
use datasets\DataInventoriesRetailCrm;
class WC_Retailcrm_Inventories_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Inventories_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $apiMock; protected $apiMock;
protected $responseMock; protected $responseMock;
protected $offer;
public function setUp() public function setUp()
{ {
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
))
->getMock(); $this->setMockResponse($this->responseMock, 'isSuccessful', true);
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('storeInventories'))
'storeInventories' ->getMock();
))
->getMock();
parent::setUp(); parent::setUp();
} }
@ -31,92 +30,103 @@ class WC_Retailcrm_Inventories_Test extends WC_Retailcrm_Test_Case_Helper
* *
* @dataProvider dataProviderLoadStocks * @dataProvider dataProviderLoadStocks
*/ */
public function test_load_stocks($retailcrm, $response) public function test_load_stocks_simple_product($retailcrm, $response)
{ {
$offer = WC_Helper_Product::create_simple_product(); $offer = WC_Helper_Product::create_simple_product();
$offer->save(); $offer->save();
if ($response['success'] == true) { if (null !== $response) {
$response['offers'][0]['externalId'] = $offer->get_id(); $response['offers'][0]['externalId'] = $offer->get_id();
$this->responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(true);
} elseif ($response['success'] == false) {
$this->responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(false);
} }
$this->responseMock->setResponse($response); $this->responseMock->setResponse($response);
if ($retailcrm) { if ($retailcrm) {
$retailcrm->expects($this->any()) $this->setMockResponse($retailcrm, 'storeInventories', $this->responseMock);
->method('storeInventories')
->willReturn($this->responseMock);
} }
$retailcrm_inventories = new WC_Retailcrm_Inventories($retailcrm); $retailcrm_inventories = new WC_Retailcrm_Inventories($retailcrm);
$result = $retailcrm_inventories->load_stocks(); $result = $retailcrm_inventories->updateQuantity();
if ($retailcrm && $response['success'] == true) { $this->checkProductData($retailcrm, $response, $result, 'simple');
$product = new WC_Product_Simple($result[0]); }
/**
* @param $retailcrm
* @param $response
*
* @dataProvider dataProviderLoadStocks
*/
public function test_load_stocks_variation_product($retailcrm, $response)
{
$offer = WC_Helper_Product::create_variation_product();
$offer->save();
$childrens = $offer->get_children();
if (null !== $response) {
$response['offers'][0]['externalId'] = $childrens[0];
}
$this->responseMock->setResponse($response);
if ($retailcrm) {
$this->setMockResponse($retailcrm, 'storeInventories', $this->responseMock);
}
$retailcrm_inventories = new WC_Retailcrm_Inventories($retailcrm);
$result = $retailcrm_inventories->updateQuantity();
$this->checkProductData($retailcrm, $response, $result, 'variation');
}
public function test_sync_off()
{
$options = $this->getOptions();
$options['sync'] = 'no';
update_option(WC_Retailcrm_Base::$option_key, $options);
$retailcrm_inventories = new WC_Retailcrm_Inventories($this->apiMock);
$result = $retailcrm_inventories->updateQuantity();
$this->assertEquals(false, $result);
}
private function checkProductData($retailcrm, $response, $result, $entity)
{
if ($retailcrm && null !== $response) {
$product = wc_get_product($result[0]);
$this->assertInstanceOf('WC_Product', $product); $this->assertInstanceOf('WC_Product', $product);
$this->assertEquals($entity, $product->get_type());
$this->assertEquals(10, $product->get_stock_quantity()); $this->assertEquals(10, $product->get_stock_quantity());
$this->assertContains($product->get_id(), $result); $this->assertEquals($result[0], $product->get_id());
$this->assertInternalType('array', $result); $this->assertInternalType('array', $result);
} elseif (null === $response) {
$this->assertEquals(false, $result);
} else { } else {
$this->assertEquals(null, $result); $this->assertEquals(null, $result);
} }
} }
private function getResponseData()
{
return array(
'true' => array(
'success' => true,
'pagination' => array(
'limit' => 250,
'totalCount' => 1,
'currentPage' => 1,
'totalPageCount' => 1
),
'offers' => array(
array(
'id' => 1,
'xmlId' => 'xmlId',
'quantity' => 10
)
)
),
'false' => array(
'success' => false,
'errorMsg' => 'Forbidden'
)
);
}
public function dataProviderLoadStocks() public function dataProviderLoadStocks()
{ {
$this->setUp(); $this->setUp();
$response = $this->getResponseData(); $response = DataInventoriesRetailCrm::getResponseData();
return array( return array(
array( array(
'retailcrm' => $this->apiMock, 'retailcrm' => $this->apiMock,
'response' => $response['true'] 'response' => $response
), ),
array( array(
'retailcrm' => false, 'retailcrm' => false,
'response' => $response['true'] 'response' => $response
), ),
array( array(
'retailcrm' => $this->apiMock, 'retailcrm' => $this->apiMock,
'response' => $response['false'] 'response' => null
),
array(
'retailcrm' => false,
'response' => $response['false']
) )
); );
} }

View File

@ -1,6 +1,6 @@
<?php <?php
class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $apiMock; protected $apiMock;
protected $order; protected $order;
@ -9,23 +9,33 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
public function setUp() public function setUp()
{ {
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(
'ordersGet', array(
'ordersCreate', 'ordersGet',
'ordersEdit', 'ordersCreate',
'customersGet', 'ordersEdit',
'customersCreate', 'customersGet',
'ordersPaymentCreate', 'customersCreate',
'ordersPaymentDelete', 'ordersPaymentCreate',
'customersList' 'ordersPaymentDelete',
)) 'customersList',
->getMock(); 'getCorporateEnabled',
'customersCorporateCompanies',
'customersCorporateList',
'customersCorporateCreate',
'getSingleSiteForKey',
'customersCorporateAddressesCreate',
'customersCorporateCompaniesCreate'
)
)
->getMock();
$this->options = $this->setOptions();
parent::setUp(); parent::setUp();
} }
/** /**
* @param $retailcrm * @param $retailcrm
* @dataProvider dataProviderRetailcrm * @dataProvider dataProviderRetailcrm
@ -33,73 +43,136 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
public function test_order_create($retailcrm) public function test_order_create($retailcrm)
{ {
if ($retailcrm) { if ($retailcrm) {
$responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $responseMock = $this->createResponseMock();
->disableOriginalConstructor() $responseMockCustomers = $this->createResponseMock();
->setMethods(array(
'isSuccessful'
))
->getMock();
$responseMockCustomers = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
$responseMockCustomers->setResponse( $responseMockCustomers->setResponse(
array('success' => true, array(
'success' => true,
'customers' => array( 'customers' => array(
array('externalId' => 1) array('externalId' => 1)
) )
) )
); );
$retailcrm->expects($this->any()) $this->setMockResponse($retailcrm, 'ordersCreate', $responseMock);
->method('customersCreate') $this->setMockResponse($retailcrm, 'customersCreate', $responseMock);
->willReturn($responseMock); $this->setMockResponse($retailcrm, 'customersList', $responseMockCustomers);
$retailcrm->expects($this->any())
->method('customersList')
->willReturn($responseMockCustomers);
} }
$this->createTestOrder(); $this->createTestOrder();
$this->options = $this->setOptions();
$retailcrm_orders = $this->getRetailcrmOrders($retailcrm); $retailcrmOrders = $this->getRetailcrmOrders($retailcrm);
$order = $retailcrm_orders->orderCreate($this->order->get_id()); $order = $retailcrmOrders->orderCreate($this->order->get_id());
$order_send = $retailcrm_orders->getOrder(); $orderData = $retailcrmOrders->getOrder();
if ($retailcrm) { if ($retailcrm) {
$this->assertInstanceOf('WC_Order', $order); $this->assertInstanceOf('WC_Order', $order);
$this->assertInternalType('array', $order_send); $this->assertInternalType('array', $orderData);
$this->assertArrayHasKey('status', $order_send); $this->assertArrayHasKey('status', $orderData);
$this->assertArrayHasKey('externalId', $order_send); $this->assertArrayHasKey('externalId', $orderData);
$this->assertArrayHasKey('firstName', $order_send); $this->assertArrayHasKey('firstName', $orderData);
$this->assertArrayHasKey('lastName', $order_send); $this->assertArrayHasKey('lastName', $orderData);
$this->assertArrayHasKey('email', $order_send); $this->assertArrayHasKey('email', $orderData);
$this->assertArrayHasKey('delivery', $order_send); $this->assertArrayHasKey('delivery', $orderData);
$this->assertArrayHasKey('code', $order_send['delivery']); $this->assertArrayHasKey('code', $orderData['delivery']);
$this->assertArrayHasKey('address', $order_send['delivery']); $this->assertArrayHasKey('address', $orderData['delivery']);
$this->assertArrayHasKey('index', $order_send['delivery']['address']); $this->assertArrayHasKey('index', $orderData['delivery']['address']);
$this->assertArrayHasKey('city', $order_send['delivery']['address']); $this->assertArrayHasKey('city', $orderData['delivery']['address']);
$this->assertEquals($this->order->get_id(), $order_send['externalId']); $this->assertEquals($this->order->get_id(), $orderData['externalId']);
$this->assertEquals('status1', $order_send['status']); $this->assertEquals('status1', $orderData['status']);
$this->assertEquals('Jeroen', $order_send['firstName']); $this->assertEquals('Jeroen', $orderData['firstName']);
$this->assertEquals('Sormani', $order_send['lastName']); $this->assertEquals('Sormani', $orderData['lastName']);
$this->assertEquals('admin@example.org', $order_send['email']); $this->assertEquals('admin@example.org', $orderData['email']);
$this->assertEquals('US', $order_send['countryIso']); $this->assertEquals('US', $orderData['countryIso']);
if (mb_strlen($order_send['delivery']['address']['index']) === 6) { if (mb_strlen($orderData['delivery']['address']['index']) === 6) {
$this->assertEquals('123456', $order_send['delivery']['address']['index']); $this->assertEquals('123456', $orderData['delivery']['address']['index']);
} else { } else {
$this->assertEquals('12345', $order_send['delivery']['address']['index']); $this->assertEquals('12345', $orderData['delivery']['address']['index']);
} }
$this->assertEquals('WooCity', $order_send['delivery']['address']['city']); $this->assertEquals('WooCity', $orderData['delivery']['address']['city']);
$this->assertEquals('delivery', $order_send['delivery']['code']); $this->assertEquals('delivery', $orderData['delivery']['code']);
$this->assertArrayHasKey('payments', $order_send); $this->assertArrayHasKey('payments', $orderData);
$this->assertInternalType('array', $order_send['payments']); $this->assertInternalType('array', $orderData['payments']);
$this->assertArrayHasKey('type', $order_send['payments'][0]); $this->assertArrayHasKey('type', $orderData['payments'][0]);
$this->assertArrayHasKey('externalId', $order_send['payments'][0]); $this->assertArrayHasKey('externalId', $orderData['payments'][0]);
$this->assertEquals('payment1', $order_send['payments'][0]['type']); $this->assertEquals('payment1', $orderData['payments'][0]['type']);
} else {
$this->assertEquals(null, $order);
}
}
/**
* @param $retailcrm
* @dataProvider dataProviderRetailcrm
*/
public function test_order_create_with_corporate_customer($retailcrm)
{
if ($retailcrm) {
$responseMock = $this->createResponseMock();
// Mock response for search customer
$responseMockSearch = $this->createResponseMock();
$this->setMockResponse($responseMockSearch, 'isSuccessful', true);
$responseMockSearch->setResponse(
array(
'success' => true,
'customersCorporate' => array()
)
);
// Mock response for create customer corporate, his addresses and companies
$responseMockCustomerCorporate = $this->createResponseMock();
$this->setMockResponse($responseMockCustomerCorporate, 'isSuccessful', true);
$responseMockCustomerCorporate->setResponse(
array(
'success' => true,
'id' => 1
)
);
// Mock response for get companies
$responseMockCompany = $this->createResponseMock();
$this->setMockResponse($responseMockCompany, 'isSuccessful', true);
$responseMockCompany->setResponse(
array(
'success' => true,
'companies' => array(
array('name' => 'WooCompany', 'id' => 777)
)
)
);
$this->setMockResponse($retailcrm, 'ordersCreate', $responseMock);
$this->setMockResponse($retailcrm, 'getSingleSiteForKey', 'woo');
$this->setMockResponse($retailcrm, 'customersCorporateCreate', $responseMockCustomerCorporate);
$this->setMockResponse($retailcrm, 'customersCorporateAddressesCreate', $responseMockCustomerCorporate);
$this->setMockResponse($retailcrm, 'customersCorporateCompaniesCreate', $responseMockCustomerCorporate);
$this->setMockResponse($retailcrm, 'customersCorporateList', $responseMockSearch);
$this->setMockResponse($retailcrm, 'getCorporateEnabled', true);
$this->setMockResponse($retailcrm, 'customersCorporateCompanies', $responseMockCompany);
}
$this->createTestOrder();
$retailcrmOrders = $this->getRetailcrmOrders($retailcrm);
$order = $retailcrmOrders->orderCreate($this->order->get_id());
$orderData = $retailcrmOrders->getOrder();
if ($retailcrm) {
$this->assertInstanceOf('WC_Order', $order);
$this->assertArrayHasKey('customer', $orderData);
$this->assertArrayHasKey('id', $orderData['customer']);
$this->assertEquals(1, $orderData['customer']['id']);
$this->assertArrayHasKey('company', $orderData);
$this->assertArrayHasKey('id', $orderData['company']);
$this->assertArrayHasKey('name', $orderData['company']);
$this->assertEquals(777, $orderData['company']['id']);
$this->assertEquals($this->order->get_billing_company(), $orderData['company']['name']);
} else { } else {
$this->assertEquals(null, $order); $this->assertEquals(null, $order);
} }
@ -114,72 +187,57 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
public function test_update_order($isSuccessful, $retailcrm) public function test_update_order($isSuccessful, $retailcrm)
{ {
$this->createTestOrder(); $this->createTestOrder();
$this->options = $this->setOptions();
if ($retailcrm) { if ($retailcrm) {
$responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $responseMock = $this->createResponseMock();
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
$responseMock->expects($this->any()) $this->setMockResponse($responseMock, 'isSuccessful', $isSuccessful);
->method('isSuccessful') $this->setMockResponse($retailcrm, 'ordersEdit', $responseMock);
->willReturn($isSuccessful); $this->setMockResponse($retailcrm, 'ordersPaymentDelete', $responseMock);
$retailcrm->expects($this->any())
->method('ordersEdit')
->willReturn($responseMock);
$retailcrm->expects($this->any())
->method('ordersPaymentDelete')
->willReturn($responseMock);
$response = $this->getResponseData($this->order->get_id()); $response = $this->getResponseData($this->order->get_id());
$responseMock->setResponse($response); $responseMock->setResponse($response);
$retailcrm->expects($this->any()) $this->setMockResponse($retailcrm, 'ordersGet', $responseMock);
->method('ordersGet')
->willReturn($responseMock);
} }
$retailcrm_orders = $this->getRetailcrmOrders($retailcrm); $retailcrmOrders = $this->getRetailcrmOrders($retailcrm);
$order = $retailcrm_orders->updateOrder($this->order->get_id()); $order = $retailcrmOrders->updateOrder($this->order->get_id());
$order_send = $retailcrm_orders->getOrder(); $orderData = $retailcrmOrders->getOrder();
if ($retailcrm) { if ($retailcrm) {
$this->assertInstanceOf('WC_Order', $order); $this->assertInstanceOf('WC_Order', $order);
$this->assertInternalType('array', $order_send); $this->assertInternalType('array', $orderData);
$this->assertArrayHasKey('status', $order_send); $this->assertArrayHasKey('status', $orderData);
$this->assertArrayHasKey('externalId', $order_send); $this->assertArrayHasKey('externalId', $orderData);
$this->assertArrayHasKey('firstName', $order_send); $this->assertArrayHasKey('firstName', $orderData);
$this->assertArrayHasKey('lastName', $order_send); $this->assertArrayHasKey('lastName', $orderData);
$this->assertArrayHasKey('email', $order_send); $this->assertArrayHasKey('email', $orderData);
$this->assertArrayHasKey('delivery', $order_send); $this->assertArrayHasKey('delivery', $orderData);
$this->assertArrayHasKey('code', $order_send['delivery']); $this->assertArrayHasKey('code', $orderData['delivery']);
$this->assertArrayHasKey('address', $order_send['delivery']); $this->assertArrayHasKey('address', $orderData['delivery']);
$this->assertArrayHasKey('index', $order_send['delivery']['address']); $this->assertArrayHasKey('index', $orderData['delivery']['address']);
$this->assertArrayHasKey('city', $order_send['delivery']['address']); $this->assertArrayHasKey('city', $orderData['delivery']['address']);
$this->assertEquals($this->order->get_id(), $order_send['externalId']); $this->assertEquals($this->order->get_id(), $orderData['externalId']);
$this->assertEquals('status1', $order_send['status']); $this->assertEquals('status1', $orderData['status']);
$this->assertEquals('Jeroen', $order_send['firstName']); $this->assertEquals('Jeroen', $orderData['firstName']);
$this->assertEquals('Sormani', $order_send['lastName']); $this->assertEquals('Sormani', $orderData['lastName']);
$this->assertEquals('admin@example.org', $order_send['email']); $this->assertEquals('admin@example.org', $orderData['email']);
$this->assertEquals('US', $order_send['countryIso']); $this->assertEquals('US', $orderData['countryIso']);
$this->assertEquals(0, $order_send['discountManualAmount']); $this->assertEquals(0, $orderData['discountManualAmount']);
$this->assertEquals(0, $order_send['discountManualPercent']); $this->assertEquals(0, $orderData['discountManualPercent']);
if (mb_strlen($order_send['delivery']['address']['index']) === 6) { if (mb_strlen($orderData['delivery']['address']['index']) === 6) {
$this->assertEquals('123456', $order_send['delivery']['address']['index']); $this->assertEquals('123456', $orderData['delivery']['address']['index']);
} else { } else {
$this->assertEquals('12345', $order_send['delivery']['address']['index']); $this->assertEquals('12345', $orderData['delivery']['address']['index']);
} }
$this->assertEquals('WooCity', $order_send['delivery']['address']['city']); $this->assertEquals('WooCity', $orderData['delivery']['address']['city']);
$this->assertEquals('delivery', $order_send['delivery']['code']); $this->assertEquals('delivery', $orderData['delivery']['code']);
$payment = $retailcrmOrders->getPayment();
$payment = $retailcrm_orders->getPayment();
$this->assertInternalType('array', $payment); $this->assertInternalType('array', $payment);
if (!empty($payment)) { if (!empty($payment)) {
@ -196,6 +254,138 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
} }
} }
public function test_is_corporate_order()
{
$this->createTestOrder();
$this->order->set_billing_company('Test');
$this->assertEquals(true, WC_Retailcrm_Orders::isCorporateOrder($this->order));
//Check not corporate order
$this->order->set_billing_company('');
$this->assertEquals(false, WC_Retailcrm_Orders::isCorporateOrder($this->order));
}
public function test_is_corporate_crm_order()
{
$this->assertEquals(
true,
WC_Retailcrm_Orders::isCorporateCrmOrder(
array(
'customer' => array(
'type' => 'customer_corporate'
)
)
)
);
//Check not corporate order
$this->assertEquals(
false,
WC_Retailcrm_Orders::isCorporateCrmOrder(
array(
'customer' => array(
'type' => 'customer'
)
)
)
);
}
public function test_is_order_customer_was_changed()
{
$this->createTestOrder();
// First case
$this->order->set_billing_company('Test');
$this->assertEquals(
true,
WC_Retailcrm_Orders::isOrderCustomerWasChanged(
$this->order,
array(
'customer' => array(
'type' => 'customer'
)
)
)
);
// Second case
$this->assertEquals(
true,
WC_Retailcrm_Orders::isOrderCustomerWasChanged(
$this->order,
array(
'customer' => array(
'type' => 'customer_corporate'
),
'company' => array(
'name' => 'Test1'
)
)
)
);
// Third case
$this->order->set_customer_id(1);
$this->assertEquals(
true,
WC_Retailcrm_Orders::isOrderCustomerWasChanged(
$this->order,
array(
'customer' => array(
'type' => 'customer_corporate',
'externalId' => 2
),
'company' => array(
'name' => 'Test'
)
)
)
);
// Fourth case
$this->order->set_billing_email('test@mail.es');
$this->assertEquals(
true,
WC_Retailcrm_Orders::isOrderCustomerWasChanged(
$this->order,
array(
'customer' => array(
'type' => 'customer_corporate',
'externalId' => 1,
'email' => 'test1@mail.es'
),
'company' => array(
'name' => 'Test'
)
)
)
);
// Customer not changed
$this->assertEquals(
false,
WC_Retailcrm_Orders::isOrderCustomerWasChanged(
$this->order,
array(
'customer' => array(
'type' => 'customer_corporate',
'externalId' => 1,
'email' => 'test@mail.es'
),
'company' => array(
'name' => 'Test'
)
)
)
);
}
public function dataProviderUpdateOrder() public function dataProviderUpdateOrder()
{ {
$this->setUp(); $this->setUp();
@ -275,12 +465,27 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
$retailcrm, $retailcrm,
$this->getOptions(), $this->getOptions(),
new WC_Retailcrm_Order_Item($this->getOptions()), new WC_Retailcrm_Order_Item($this->getOptions()),
new WC_Retailcrm_Order_Address, new WC_Retailcrm_Order_Address(),
new WC_Retailcrm_Customers( new WC_Retailcrm_Customers(
$retailcrm, $this->getOptions(), new WC_Retailcrm_Customer_Address $retailcrm,
$this->getOptions(),
new WC_Retailcrm_Customer_Address()
), ),
new WC_Retailcrm_Order($this->getOptions()), new WC_Retailcrm_Order($this->getOptions()),
new WC_Retailcrm_Order_Payment($this->getOptions()) new WC_Retailcrm_Order_Payment($this->getOptions())
); );
} }
/**
* @return mixed
*/
private function createResponseMock()
{
return $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array('isSuccessful'))
->getMock();
}
} }

View File

@ -1,50 +1,58 @@
<?php <?php
class WC_Retailcrm_Plugin_Test extends WC_Retailcrm_Test_Case_Helper class WC_Retailcrm_Plugin_Test extends WC_Retailcrm_Test_Case_Helper
{ {
protected $apiMock; protected $apiMock;
protected $responseMock; protected $responseMock;
protected $plugin;
private $path = __DIR__ . '/src/retailcrm.php';
public function setUp() public function setUp()
{ {
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper') $this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful' ->getMock();
))
->getMock();
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('integrationModulesEdit'))
'marketplaceSettingsEdit' ->getMock();
))
->getMock(); $this->plugin = WC_Retailcrm_Plugin::getInstance($this->path);
parent::setUp(); parent::setUp();
} }
/** /**
* @param $retailcrm * @param $retailcrm
* @param $response * @param $responseStatus
* *
* @dataProvider dataProviderIntegrationModule * @dataProvider dataProviderIntegrationModule
*/ */
public function test_integration_module($retailcrm, $response) public function test_integration_module($retailcrm, $responseStatus)
{ {
$this->setMockResponse($this->responseMock, 'isSuccessful', $responseStatus);
$this->responseMock->setResponse(array('success' => $responseStatus));
if ($retailcrm) {
$this->setMockResponse($retailcrm, 'integrationModulesEdit', $this->responseMock);
}
$client_id = uniqid(); $client_id = uniqid();
$result = WC_Retailcrm_Plugin::integration_module($retailcrm, $client_id); $result = WC_Retailcrm_Plugin::integration_module($retailcrm, $client_id);
if (!$retailcrm || $response['success'] == false) { if (!$retailcrm || !$responseStatus) {
$this->assertEquals(false, $result); $this->assertEquals(false, $result);
} else { } else {
$this->assertEquals(true, $result); $this->assertEquals(true, $result);
} }
} }
public function test_filter_cron_schedules() public function test_filter_cron_schedules()
{ {
$plugin = WC_Retailcrm_Plugin::getInstance(dirname(__DIR__ . '/../src/retailcrm.php')); $schedules = $this->plugin->filter_cron_schedules(array());
$schedules = $plugin->filter_cron_schedules(array());
$this->assertNotEmpty($schedules['five_minutes']); $this->assertNotEmpty($schedules['five_minutes']);
$this->assertEquals(300, $schedules['five_minutes']['interval']); $this->assertEquals(300, $schedules['five_minutes']['interval']);
@ -54,77 +62,68 @@ class WC_Retailcrm_Plugin_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertEquals(900, $schedules['fiveteen_minutes']['interval']); $this->assertEquals(900, $schedules['fiveteen_minutes']['interval']);
} }
private function getResponseData() public function test_deactivate()
{ {
return array( wp_schedule_event(time(), 'three_hours', 'retailcrm_icml');
"true" => array( wp_schedule_event(time(), 'five_minutes', 'retailcrm_history');
"success" => true wp_schedule_event(time(), 'fiveteen_minutes', 'retailcrm_inventories');
),
"false" => array( $this->plugin->deactivate();
"success" => false,
"errorMsg" => "Forbidden" $this->assertEquals(false, wp_next_scheduled('retailcrm_icml'));
) $this->assertEquals(false, wp_next_scheduled('retailcrm_history'));
); $this->assertEquals(false, wp_next_scheduled('retailcrm_inventories'));
}
public function test_register_deactivation_and_activation_hook()
{
global $wp_filter;
$this->plugin->register_activation_hook();
$this->plugin->register_deactivation_hook();
$actions = array();
foreach (array_keys($wp_filter) as $key) {
if (false !== strpos($key, 'retailcrm')) {
if (false !== strpos($key, 'deactivate_')) {
$actions['deactivate'] = $key;
}
if (false !== strpos($key, 'activate_')) {
$actions['activate'] = $key;
}
}
}
$this->assertArrayHasKey('deactivate', $actions);
$this->assertNotEmpty($actions['deactivate']);
$this->assertArrayHasKey('activate', $actions);
$this->assertNotEmpty($actions['activate']);
} }
public function dataProviderIntegrationModule() public function dataProviderIntegrationModule()
{ {
$this->setUp(); $this->setUp();
$responseData = $this->getResponseData();
return array( return array(
array( array(
'retailcrm' => $this->getApiMock($responseData['true']), 'retailcrm' => $this->apiMock,
'response' => $responseData['true'] 'responseStatus' => true
), ),
array( array(
'retailcrm' => false, 'retailcrm' => false,
'response' => $responseData['true'] 'responseStatus' => true
), ),
array( array(
'retailcrm' => $this->getApiMock($responseData['false']), 'retailcrm' => $this->apiMock,
'response' => $responseData['false'] 'responseStatus' => false
), ),
array( array(
'retailcrm' => false, 'retailcrm' => false,
'response' => $responseData['false'] 'responseStatus' => false
) ),
); );
} }
private function getApiMock($response)
{
$responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
if ($response['success'] == true) {
$responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(true);
} elseif ($response['success'] == false) {
$responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(false);
}
$responseMock->setResponse($response);
$apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor()
->setMethods(array(
'integrationModulesEdit'
))
->getMock();
$apiMock->expects($this->any())
->method('integrationModulesEdit')
->willReturn($responseMock);
return $apiMock;
}
} }

View File

@ -5,14 +5,13 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
protected $apiMock; protected $apiMock;
protected $responseMock; protected $responseMock;
protected $customer; protected $customer;
private $order;
public function setUp() public function setUp()
{ {
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response') $this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array( ->setMethods(array('isSuccessful'))
'isSuccessful'
))
->getMock(); ->getMock();
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy') $this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
@ -23,17 +22,21 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
'uploadArchiveCustomers', 'uploadArchiveCustomers',
'uploadArchiveOrders', 'uploadArchiveOrders',
'getCountUsers', 'getCountUsers',
'getCountOrders' 'getCountOrders',
'customersGet',
'customersList',
'ordersCreate'
)) ))
->getMock(); ->getMock();
$this->responseMock->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$this->apiMock->expects($this->any()) $this->setMockResponse($this->responseMock, 'isSuccessful', true);
->method('customersCreate') $this->setMockResponse(
->willReturn($this->responseMock); $this->apiMock,
'customersList',
array('success' => true, 'customers' => array(array('externalId' => 1)))
);
$this->setMockResponse($this->apiMock, 'customersCreate', $this->responseMock);
$this->customer = new WC_Customer(); $this->customer = new WC_Customer();
$this->customer->set_first_name('Tester'); $this->customer->set_first_name('Tester');
@ -44,8 +47,9 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
$this->customer->set_billing_phone('89000000000'); $this->customer->set_billing_phone('89000000000');
$this->customer->set_date_created(date('Y-m-d H:i:s')); $this->customer->set_date_created(date('Y-m-d H:i:s'));
$this->customer->save(); $this->customer->save();
}
$this->order = WC_Helper_Order::create_order();
}
/** /**
* @param retailcrm * @param retailcrm
@ -65,7 +69,6 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
} }
} }
/** /**
* @param $retailcrm * @param $retailcrm
* @dataProvider dataProviderApiClient * @dataProvider dataProviderApiClient
@ -82,23 +85,21 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
} }
} }
public function test_get_count_orders_upload()
/**
* @param retailcrm
* @dataProvider dataProviderApiClient
*/
public function test_get_count_orders_upload($retailcrm)
{ {
$retailcrm_uploader = $this->getRetailcrmUploader($retailcrm); $retailcrm_uploader = $this->getRetailcrmUploader($this->apiMock);
$data = $retailcrm_uploader->getCountOrders(); $count_orders = $retailcrm_uploader->getCountOrders();
if ($retailcrm) { $this->assertInternalType('int', $count_orders);
$this->assertInternalType('int', $data);
} else {
$this->assertEquals(null, $data);
}
} }
public function test_get_count_users_upload()
{
$retailcrm_uploader = $this->getRetailcrmUploader($this->apiMock);
$count_users = $retailcrm_uploader->getCountUsers();
$this->assertInternalType('int', $count_users);
}
public function dataProviderApiClient() public function dataProviderApiClient()
{ {
@ -131,10 +132,8 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
$retailcrm, $retailcrm,
$this->getOptions(), $this->getOptions(),
new WC_Retailcrm_Order_Item($this->getOptions()), new WC_Retailcrm_Order_Item($this->getOptions()),
new WC_Retailcrm_Order_Address, new WC_Retailcrm_Order_Address(),
new WC_Retailcrm_Customers( new WC_Retailcrm_Customers($retailcrm, $this->getOptions(), new WC_Retailcrm_Customer_Address()),
$retailcrm, $this->getOptions(), new WC_Retailcrm_Customer_Address
),
new WC_Retailcrm_Order($this->getOptions()), new WC_Retailcrm_Order($this->getOptions()),
new WC_Retailcrm_Order_Payment($this->getOptions()) new WC_Retailcrm_Order_Payment($this->getOptions())
); );
@ -142,4 +141,3 @@ class WC_Retailcrm_Uploader_Test extends WC_Retailcrm_Test_Case_Helper
return new WC_Retailcrm_Uploader($retailcrm, $order, $customer); return new WC_Retailcrm_Uploader($retailcrm, $order, $customer);
} }
} }