1
0
mirror of synced 2025-01-18 17:01:41 +03:00

Fix delivery and payment methods, add history tests

This commit is contained in:
Akolzin Dmitry 2018-07-19 12:16:30 +03:00
parent f301687739
commit 59e9c69f5b
17 changed files with 638 additions and 211 deletions

View File

@ -31,6 +31,6 @@ deploy:
provider: script
script: make
on:
php: 7.1
php: 7.2
branch: master
condition: "$DEPLOY = true"

View File

@ -1,3 +1,8 @@
## 2018-07-19 v3.2.0
* Улучшен метод выробки данных о доставках и оплатах в настройках плагина
* Исправлены ошибки при обработке истории изменений
* Добавлены тесты для обработки истории изменений
## 2018-06-19 v3.1.1
* Исправлен код отправки данных в UA
* Добавлены новые фильтры, добавлена передача новых параметров в существущие

View File

@ -1 +1 @@
3.1.1
3.2.0

View File

@ -198,7 +198,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* Upload archive customers and order to retailCRM
*/
public function upload_to_crm() {
public function upload_to_crm()
{
if (!class_exists('WC_Retailcrm_Orders')) {
include_once(self::checkCustomFile('orders'));
}
@ -219,7 +220,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
update_option(self::$option_key, $options);
}
public function ajax_upload() {
public function ajax_upload()
{
$ajax_url = admin_url('admin-ajax.php');
?>
<script type="text/javascript">
@ -237,7 +239,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
<?php
}
public function ajax_generate_icml() {
public function ajax_generate_icml()
{
$ajax_url = admin_url('admin-ajax.php');
?>
<script type="text/javascript">
@ -255,7 +258,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
<?php
}
public function ajax_selected_order() {
public function ajax_selected_order()
{
$ajax_url = admin_url('admin-ajax.php');
$ids = $this->plugin_id . $this->id . '_single_order';
?>
@ -281,7 +285,12 @@ if (!class_exists('WC_Retailcrm_Base')) {
* Create customer in retailCRM
* @param int $customer_id
*/
public function create_customer($customer_id) {
public function create_customer($customer_id)
{
if (WC_Retailcrm_Plugin::history_running() === true) {
return;
}
if (!class_exists( 'WC_Retailcrm_Customers')) {
include_once(self::checkCustomFile('customers'));
}
@ -294,7 +303,12 @@ if (!class_exists('WC_Retailcrm_Base')) {
* Edit customer in retailCRM
* @param int $customer_id
*/
public function update_customer($customer_id) {
public function update_customer($customer_id)
{
if (WC_Retailcrm_Plugin::history_running() === true) {
return;
}
if (!class_exists('WC_Retailcrm_Customers')) {
include_once(self::checkCustomFile('customers'));
}
@ -307,7 +321,12 @@ if (!class_exists('WC_Retailcrm_Base')) {
* Edit order in retailCRM
* @param int $order_id
*/
public function update_order($order_id) {
public function update_order($order_id)
{
if (WC_Retailcrm_Plugin::history_running() === true) {
return;
}
if (!class_exists('WC_Retailcrm_Orders')) {
include_once(self::checkCustomFile('orders'));
}
@ -319,7 +338,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* Init google analytics code
*/
public function initialize_analytics() {
public function initialize_analytics()
{
if (!class_exists('WC_Retailcrm_Google_Analytics')) {
include_once(self::checkCustomFile('ga'));
}
@ -335,7 +355,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* Google analytics send code
*/
public function send_analytics() {
public function send_analytics()
{
if (!class_exists('WC_Retailcrm_Google_Analytics')) {
include_once(self::checkCustomFile('ga'));
}
@ -351,8 +372,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* Initialize integration settings form fields.
*/
public function init_form_fields() {
public function init_form_fields()
{
$this->form_fields = array(
array( 'title' => __( 'General Options', 'retailcrm' ), 'type' => 'title', 'desc' => '', 'id' => 'general_options' ),
@ -506,7 +527,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
'id' => 'payment_options'
);
foreach ($wc_payment->get_available_payment_gateways() as $payment) {
foreach ($wc_payment->payment_gateways() as $payment) {
if (isset($payment->enabled) && $payment->enabled == 'yes') {
$this->form_fields[$payment->id] = array(
'title' => __($payment->method_title, 'woocommerce'),
@ -629,7 +650,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
* Generate icml file
*/
$this->form_fields[] = array(
'title' => __( 'Generate ICML catalog', 'retailcrm' ),
'title' => __('Generate ICML catalog', 'retailcrm'),
'type' => 'title',
'description' => '',
'id' => 'icml_options'
@ -648,7 +669,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
* Upload single order
*/
$this->form_field[] = array(
'title' => __( 'Upload single order by id', 'retailcrm' ),
'title' => __('Upload single order by id', 'retailcrm'),
'type' => 'title',
'description' => '',
'id' => 'order_options'
@ -682,7 +703,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return string
*/
public function generate_button_html( $key, $data ) {
public function generate_button_html($key, $data)
{
$field = $this->plugin_id . $this->id . '_' . $key;
$defaults = array(
'class' => 'button-secondary',
@ -722,7 +744,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return string
*/
public function generate_heading_html($key, $data) {
public function generate_heading_html($key, $data)
{
$field_key = $this->get_field_key( $key );
$defaults = array(
'title' => '',
@ -752,7 +775,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return string
*/
public function validate_api_version_field($key, $value) {
public function validate_api_version_field($key, $value)
{
$post = $this->get_post_data();
$versionMap = array(
@ -785,7 +809,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return string
*/
public function validate_api_url_field($key, $value) {
public function validate_api_url_field($key, $value)
{
$post = $this->get_post_data();
$api = new WC_Retailcrm_Proxy(
$value,
@ -810,7 +835,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return string
*/
public function validate_api_key_field( $key, $value ) {
public function validate_api_key_field($key, $value)
{
$post = $this->get_post_data();
$api = new WC_Retailcrm_Proxy(
$post[$this->plugin_id . $this->id . '_api_url'],
@ -834,7 +860,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
/**
* Scritp show|hide block settings
*/
function show_blocks() {
function show_blocks()
{
?>
<script type="text/javascript">
jQuery('h2.retailcrm_hidden').hover().css({
@ -860,7 +887,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
*
* @return bool|WC_Retailcrm_Proxy
*/
public function getApiClient() {
public function getApiClient()
{
if ($this->get_option('api_url') && $this->get_option('api_key')) {
return new WC_Retailcrm_Proxy(
$this->get_option('api_url'),

View File

@ -23,7 +23,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
/**
* WC_Retailcrm_History constructor.
* @param bool $retailcrm
* @param $retailcrm (default = false)
*/
public function __construct($retailcrm = false)
{
@ -93,7 +93,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
continue;
}
$this->removeFuncsHook();
WC_Retailcrm_Plugin::$history_run = true;
if ($record['field'] == 'first_name' && isset($record['customer']['externalId'])) {
if ($record['newValue']){
@ -143,7 +143,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
}
}
$this->addFuncsHook();
WC_Retailcrm_Plugin::$history_run = false;
}
}
@ -186,7 +186,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
continue;
}
$this->removeFuncsHook();
WC_Retailcrm_Plugin::$history_run = true;
try {
$this->orderEdit($record, $options);
@ -200,7 +200,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
continue;
}
$this->addFuncsHook();
WC_Retailcrm_Plugin::$history_run = false;
}
}
@ -211,35 +211,6 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
update_option('retailcrm_orders_history_since_id', $new_since_id);
}
/**
* Remove function hooks before download history changes
*
* @return void
*/
protected function removeFuncsHook()
{
remove_action('woocommerce_update_order', 'update_order', 11, 1);
remove_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
/**
* Add function hooks after downloading history changes
*
* @return void
*/
protected function addFuncsHook()
{
if (!has_action('woocommerce_update_order', 'update_order')) {
add_action('woocommerce_update_order', 'update_order', 11, 1);
}
if (!has_action('woocommerce_checkout_update_user_meta', 'update_customer')) {
add_action('woocommerce_checkout_update_user_meta', 'update_customer', 10, 2);
}
if (!has_action('woocommerce_order_status_changed', 'retailcrm_update_order_status')) {
add_action('woocommerce_order_status_changed', 'retailcrm_update_order_status', 11, 1);
}
}
/**
* Edit order in WC
*
@ -252,22 +223,19 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
if ($record['field'] == 'status' && !empty($record['newValue']) && !empty($record['oldValue'])) {
$newStatus = $record['newValue']['code'];
if (!empty($options[$newStatus]) && !empty($record['order']['externalId'])) {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->update_status($options[$newStatus]);
}
}
elseif ($record['field'] == 'order_product' && $record['newValue']) {
$product = wc_get_product($record['item']['offer']['externalId']);
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->add_product($product, $record['item']['quantity']);
$this->update_total($order);
}
elseif ($record['field'] == 'order_product.quantity' && $record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$product = wc_get_product($record['item']['offer']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
@ -275,19 +243,17 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
wc_delete_order_item($order_item_id);
$product = wc_get_product($offer_id);
$order->add_product($product, $record['newValue']);
}
}
$newOrder = wc_get_order($record['order']['externalId']);
$this->update_total($newOrder);
}
elseif ($record['field'] == 'order_product' && !$record['newValue']) {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$items = $order->get_items();
foreach ($items as $order_item_id => $item) {
@ -295,89 +261,51 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$offer_id = $item['variation_id'];
} else {
$offer_id = $item['product_id'];
}
}
if ($offer_id == $record['item']['offer']['externalId']) {
wc_delete_order_item($order_item_id);
$this->update_total($order);
wc_delete_order_item($order_item_id);
}
}
}
elseif ($record['field'] == 'delivery_type') {
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
if (isset($options[$newValue])) {
$order = new WC_Order($record['order']['externalId']);
$items = $order->get_items('shipping');
$item_id = $this->getShippingItemId($items);
$crmOrder = $this->retailcrm->ordersGet($record['order']['externalId']);
$shipping_methods = get_wc_shipping_methods(true);
if (isset($shipping_methods[$options[$newValue]])) {
$method_id = $options[$newValue];
} else {
$method_id = explode(':', $options[$newValue]);
$method_id = $method_id[0];
$shipping_method = $shipping_methods[$method_id]['shipping_methods'][$options[$newValue]];
}
if (is_object($crmOrder)) {
if ($crmOrder->isSuccessful()) {
$deliveryCost = isset($crmOrder['order']['delivery']['cost']) ? $crmOrder['order']['delivery']['cost'] : 0;
}
}
$args = array(
'method_id' => $options[$newValue],
'method_title' => isset($shipping_method) ? $shipping_method['title'] : $shipping_methods[$options[$newValue]]['name'],
'total' => isset($deliveryCost) ? $deliveryCost : 0
);
$item = $order->get_item((int)$item_id);
if (!$item) {
return false;
}
$item->set_order_id((int)$order->get_id());
$item->set_props($args);
$item->save();
}
$updateOrder = new WC_Order((int)$order->get_id());
$this->update_total($updateOrder);
}
elseif ($record['field'] == 'delivery_type'
|| $record['field'] == 'delivery_cost'
|| $record['field'] == 'delivery_net_cost'
|| $record['field'] == 'delivery_service'
) {
$newValue = isset($record['newValue']['code']) ? $record['newValue']['code'] : $record['newValue'];
$this->updateShippingItemId($record['field'], $newValue, $record['order']['externalId'], $options);
}
elseif ($record['field'] == 'delivery_address.region') {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->set_shipping_state($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.city') {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->set_shipping_city($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.street') {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->set_shipping_address_1($record['newValue']);
}
elseif ($record['field'] == 'delivery_address.building') {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$order->set_shipping_address_2($record['newValue']);
}
elseif ($record['field'] == 'payment_type') {
$order = new WC_Order($record['order']['externalId']);
$order = wc_get_order($record['order']['externalId']);
$newValue = $record['newValue']['code'];
if (!empty($options[$newValue]) && !empty($record['order']['externalId'])) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
$payment = WC_Payment_Gateways::instance();
$payment_types = $payment->payment_gateways();
if (isset($payment_types[$options[$newValue]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
$order->set_payment_method($payment_types[$options[$newValue]]);
}
}
}
@ -387,15 +315,15 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
if ($response->isSuccessful()) {
$order_data = $response['order'];
$order = new WC_Order($record['order']['externalId']);
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
$order = wc_get_order($record['order']['externalId']);
$payment = WC_Payment_Gateways::instance();
$payment_types = $payment->payment_gateways();
if (count($order_data['payments']) == 1) {
$paymentType = end($order_data['payments']);
if (isset($payment_types[$options[$paymentType['type']]])) {
$payment = $payment_types[$options[$paymentType['type']]];
update_post_meta($order->get_id(), '_payment_method', $payment->id);
$payment_type = $payment_types[$options[$paymentType['type']]];
$order->set_payment_method($payment_type);
}
} else {
foreach ($order_data['payments'] as $payment_data) {
@ -409,7 +337,7 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
}
if (isset($payment_types[$options[$paymentType['type']]])) {
update_post_meta($order->get_id(), '_payment_method', $payment->id);
$order->set_payment_method($payment_types[$options[$paymentType['type']]]);
}
}
}
@ -437,20 +365,17 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
);
$order_record = $record['order'];
$order_data = wc_create_order($args);
$order = new WC_Order($order_data->get_id());
$order = wc_create_order($args);
$address_shipping = array(
'first_name' => $order_record['firstName'],
'last_name' => isset($order_record['lastName']) ? $order_record['lastName'] : '',
'company' => '',
'email' => isset($order_record['email']) ? $order_record['email'] : '',
'phone' => isset($order_record['phone']) ? $order_record['phone'] : '',
'address_1' => isset($order_record['delivery']['address']['text']) ? $order_record['delivery']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['delivery']['address']['city']) ? $order_record['delivery']['address']['city'] : '',
'state' => isset($order_record['delivery']['address']['region']) ? $order_record['delivery']['address']['region'] : '',
'postcode' => isset($order_record['delivery']['address']['postcode']) ? $order_record['delivery']['address']['postcode'] : '',
'postcode' => isset($order_record['delivery']['address']['index']) ? $order_record['delivery']['address']['index'] : '',
'country' => $order_record['delivery']['address']['countryIso']
);
@ -459,21 +384,21 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
'last_name' => isset($order_record['customer']['lastName']) ? $order_record['customer']['lastName'] : '',
'company' => '',
'email' => isset($order_record['customer']['email']) ? $order_record['customer']['email'] : '',
'phone' => isset($order_record['customer'][0]['number']) ? $order_record['customer'][0]['number'] : '',
'phone' => isset($order_record['customer']['phones'][0]['number']) ? $order_record['customer']['phones'][0]['number'] : '',
'address_1' => isset($order_record['customer']['address']['text']) ? $order_record['customer']['address']['text'] : '',
'address_2' => '',
'city' => isset($order_record['customer']['address']['city']) ? $order_record['customer']['address']['city'] : '',
'state' => isset($order_record['customer']['address']['region']) ? $order_record['customer']['address']['region'] : '',
'postcode' => isset($order_record['customer']['address']['postcode']) ? $order_record['customer']['address']['postcode'] : '',
'postcode' => isset($order_record['customer']['address']['index']) ? $order_record['customer']['address']['index'] : '',
'country' => $order_record['customer']['address']['countryIso']
);
if ($this->retailcrm_settings['api_version'] == 'v5') {
if ($order_record['payments']) {
$payment = new WC_Payment_Gateways();
if ($this->retailcrm_settings['api_version'] == 'v5') {
if (isset($order_record['payments']) && $order_record['payments']) {
$payment = WC_Payment_Gateways::instance();
if (count($order_record['payments']) == 1) {
$payment_types = $payment->get_available_payment_gateways();
$payment_types = $payment->payment_gateways();
$payments = $order_record['payments'];
$paymentType = end($payments);
@ -484,8 +409,8 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
}
} else {
if (isset($order_record['paymentType']) && $order_record['paymentType']) {
$payment = new WC_Payment_Gateways();
$payment_types = $payment->get_available_payment_gateways();
$payment = WC_Payment_Gateways::instance();
$payment_types = $payment->payment_gateways();
if (isset($options[$order_record['paymentType']]) && isset($payment_types[$options[$order_record['paymentType']]])) {
$order->set_payment_method($payment_types[$options[$order_record['paymentType']]]);
@ -507,71 +432,97 @@ if ( ! class_exists( 'WC_Retailcrm_History' ) ) :
$deliveryCode = isset($order_record['delivery']['code']) ? $order_record['delivery']['code'] : false;
if ($deliveryCode && isset($options[$deliveryCode])) {
$delivery = explode(':', $options[$deliveryCode]);
$shipping = new WC_Order_Item_Shipping();
$shipping_methods = get_wc_shipping_methods();
$shipping->set_method_title($shipping_methods[$options[$deliveryCode]]['name']);
$shipping->set_method_id($options[$deliveryCode]);
if (isset($delivery[1])) {
$instance_id = $delivery[1];
}
}
if (isset($order_record['delivery']['service']['code'])) {
$service = retailcrm_get_delivery_service(
$shipping->get_method_id(),
$order_record['delivery']['service']['code']
);
if (isset($options[$deliveryCode])) {
if (isset($instance_id)) {
$wc_shipping = WC_Shipping_Zones::get_shipping_method($instance_id);
$shipping_method_title = $wc_shipping->method_title;
$shipping_method_id = $options[$deliveryCode];
$shipping_total = $order_record['delivery']['cost'];
} else {
$wc_shipping = new WC_Shipping();
$wc_shipping_types = $wc_shipping->get_shipping_methods();
foreach ($wc_shipping_types as $shipping_type) {
if ($shipping_type->id == $options[$deliveryCode]) {
$shipping_method_id = $shipping_type->id;
$shipping_method_title = $shipping_type->method_title;
$shipping_total = $order_record['delivery']['cost'];
}
if ($service) {
$shipping->set_instance_id($order_record['delivery']['service']['code']);
}
}
$shipping = new WC_Order_Item_Shipping();
$shipping->set_props( array(
'method_title' => $shipping_method_title,
'method_id' => $shipping_method_id,
'total' => wc_format_decimal($shipping_total),
'order_id' => $order->get_id()
) );
if (!wc_tax_enabled()) {
$shipping->set_total($order_record['delivery']['cost']);
} else {
$shipping->set_total($order_record['delivery']['netCost']);
}
$shipping->set_order_id($order->get_id());
$shipping->save();
$order->add_item($shipping);
}
}
$this->update_total($order);
$ids[] = array(
'id' => (int)$order_record['id'],
'externalId' => (int)$order_data->get_id()
'externalId' => (int)$order->get_id()
);
$this->retailcrm->ordersFixExternalIds($ids);
}
if (isset($record['order']['externalId']) && !empty($record['order']['externalId'])) {
$newOrder = wc_get_order($record['order']['externalId']);
$this->update_total($newOrder);
}
}
/**
* Get shipping
*
* @param array $items
*
* @return int
* Update shipping
*
* @param string $field
* @param string $new_value
* @param string $order_id
* @param array $options
*
* @return mixed
*/
protected function getShippingItemId($items)
protected function updateShippingItemId($field, $new_value, $order_id, $options)
{
if ($items) {
foreach ($items as $key => $value) {
$item_id[] = $key;
$order = wc_get_order($order_id);
$shippings = $order->get_items('shipping');
$shipping = reset($shippings);
if ($field == 'delivery_type') {
if (!isset($options[$new_value])) {
return false;
}
$shipping_methods = get_wc_shipping_methods();
$shipping->set_method_title($shipping_methods[$options[$new_value]]['name']);
$shipping->set_method_id($options[$new_value]);
}
if ($field == 'delivery_cost' && !wc_tax_enabled()) {
$shipping->set_total($new_value);
}
if ($field == 'delivery_net_cost' && wc_tax_enabled()) {
$shipping->set_total($new_value);
}
if ($field == 'delivery_service') {
$service = retailcrm_get_delivery_service($shipping->get_method_id(), $new_value);
if ($service) {
$shipping->set_instance_id($new_value);
}
}
return $item_id[0];
$data_store = WC_Data_Store::load('order-item-shipping');
$data_store->update($shipping);
$updateOrder = wc_get_order((int)$order->get_id());
$this->update_total($updateOrder);
return true;
}
/**

View File

@ -110,7 +110,7 @@ if ( ! class_exists( 'WC_Retailcrm_Icml' ) ) :
{
$string = sprintf(
'<?xml version="1.0" encoding="UTF-8"?><yml_catalog date="%s"><shop><name>%s</name><categories/><offers/></shop></yml_catalog>',
date('Y-m-d H:i:s'),
current_time('Y-m-d H:i:s'),
$this->shop
);

View File

@ -247,14 +247,25 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
if (isset($this->retailcrm_settings[$shipping['method_id']])) {
$shipping_method = $shipping['method_id'];
} else {
} elseif (isset($this->retailcrm_settings[$shipping_code[0]])) {
$shipping_method = $shipping_code[0];
} else {
$shipping_method = $shipping['method_id'] . ':' . $shipping['instance_id'];
}
$shipping_cost = $shipping['cost'];
$shipping_cost = $shipping['total'] + $shipping['total_tax'];
if (!empty($shipping_method) && !empty($this->retailcrm_settings[$shipping_method])) {
$order_data['delivery']['code'] = $this->retailcrm_settings[$shipping_method];
$service = retailcrm_get_delivery_service($shipping['method_id'], $shipping['instance_id']);
if ($service) {
$order_data['delivery']['service'] = array(
'name' => $service['title'],
'code' => $service['instance_id'],
'active' => true
);
}
}
if (!empty($shipping_cost)) {
@ -272,7 +283,6 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$user_data_billing = $order->get_address('billing');
if (!empty($user_data_billing)) {
if (!empty($user_data_billing['phone'])) $order_data['phone'] = $user_data_billing['phone'];
if (!empty($user_data_billing['email'])) $order_data['email'] = $user_data_billing['email'];
if (!empty($user_data_billing['first_name'])) $order_data['firstName'] = $user_data_billing['first_name'];
@ -286,7 +296,6 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
$user_data = $order->get_address('shipping');
if (!empty($user_data)) {
if (!empty($user_data['phone'])) $order_data['phone'] = $user_data['phone'];
if (!empty($user_data['email'])) $order_data['email'] = $user_data['email'];
if (!empty($user_data['first_name'])) $order_data['firstName'] = $user_data['first_name'];
@ -294,7 +303,7 @@ if ( ! class_exists( 'WC_Retailcrm_Orders' ) ) :
if (!empty($user_data['postcode'])) $order_data['delivery']['address']['index'] = $user_data['postcode'];
if (!empty($user_data['city'])) $order_data['delivery']['address']['city'] = $user_data['city'];
if (!empty($user_data['state'])) $order_data['delivery']['address']['region'] = $user_data['state'];
if (!empty($user_data['country'])) $order_data['countryIso'] = $user_data['country'];
if (!empty($user_data['country'])) $order_data['delivery']['address']['countryIso'] = $user_data['country'];
}
$order_data['delivery']['address']['text'] = sprintf(

View File

@ -3,7 +3,7 @@
class WC_Retailcrm_Plugin {
public $file;
public static $history_run = false;
private static $instance = null;
public static function getInstance($file) {
@ -40,16 +40,21 @@ class WC_Retailcrm_Plugin {
}
public function deactivate() {
if ( wp_next_scheduled ( 'retailcrm_icml' )) {
if (wp_next_scheduled('retailcrm_icml')) {
wp_clear_scheduled_hook('retailcrm_icml');
}
if ( wp_next_scheduled ( 'retailcrm_history' )) {
if (wp_next_scheduled('retailcrm_history')) {
wp_clear_scheduled_hook('retailcrm_history');
}
if ( wp_next_scheduled ( 'retailcrm_inventories' )) {
if (wp_next_scheduled('retailcrm_inventories')) {
wp_clear_scheduled_hook('retailcrm_inventories');
}
}
public static function history_running()
{
return self::$history_run;
}
}

View File

@ -4,11 +4,18 @@ if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
function get_wc_shipping_methods($enhanced = false) {
function get_wc_shipping_methods_by_zones($enhanced = false) {
$result = array();
$shippingZonesObj = new WC_Shipping_Zones();
$shippingZones = $shippingZonesObj->get_zones();
$shippingZones = WC_Shipping_Zones::get_zones();
$defaultZone = WC_Shipping_Zones::get_zone_by();
$shippingZones[$defaultZone->get_id()] = array(
$defaultZone->get_data(),
'zone_id' => $defaultZone->get_id(),
'formatted_zone_location' => $defaultZone->get_formatted_location(),
'shipping_methods' => $defaultZone->get_shipping_methods(false)
);
if ($shippingZones) {
foreach ($shippingZones as $code => $shippingZone) {
@ -42,5 +49,36 @@ function get_wc_shipping_methods($enhanced = false) {
}
}
return $result;
}
function get_wc_shipping_methods() {
$wc_shipping = WC_Shipping::instance();
$shipping_methods = $wc_shipping->get_shipping_methods();
$result = array();
foreach ($shipping_methods as $code => $shipping) {
$result[$code] = array(
'name' => $shipping->method_title,
'enabled' => $shipping->enabled,
'description' => $shipping->method_description,
'title' => $shipping->title ? $shipping->title : $shipping->method_title
);
}
return apply_filters('retailcrm_shipping_list', $result);
}
function retailcrm_get_delivery_service($method_id, $instance_id) {
$shippings_by_zone = get_wc_shipping_methods_by_zones(true);
$method = explode(':', $method_id);
$method_id = $method[0];
$shipping = isset($shippings_by_zone[$method_id]) ? $shippings_by_zone[$method_id] : array();
if ($shipping && isset($shipping['shipping_methods'][$method_id . ':' . $instance_id])) {
return $shipping['shipping_methods'][$method_id . ':' . $instance_id];
}
return false;
}

View File

@ -45,6 +45,11 @@ API-ключ должен быть для отдельного магазина
2. В появившихся списках справочников настройте соответствие способов доставки и оплаты, а так же статусов заказов. Отметьте галочку "Выгружать остатки", если хотите выгружать остатки из Retailcrm в магазин (подробнее смотрите в описании).
== Changelog ==
= 3.2.0 =
* Улучшен метод выробки данных о доставках и оплатах в настройках плагина
* Исправлены ошибки при обработке истории изменений
* Добавлены тесты для обработки истории изменений
= 3.1.1 =
* Исправлен код отправки данных в UA
* Добавлены новые фильтры, добавлена передача новых параметров в существущие
@ -127,6 +132,11 @@ API-ключ должен быть для отдельного магазина
== Upgrade Notice ==
= 3.2.0 =
Улучшен метод выробки данных о доставках и оплатах в настройках плагина
Исправлены ошибки при обработке истории изменений
Добавлены тесты для обработки истории изменений
= 3.1.1 =
Исправлен код отправки данных в UA
Добавлены новые фильтры, добавлена передача новых параметров в существущие

View File

@ -1,8 +1,8 @@
<?php
/**
* Version: 3.1.1
* Version: 3.2.0
* WC requires at least: 3.0
* WC tested up to: 3.3
* WC tested up to: 3.4.3
* Plugin Name: WooCommerce RetailCRM
* Plugin URI: https://wordpress.org/plugins/woo-retailcrm/
* Description: Integration plugin for WooCommerce & RetailCRM

View File

@ -15,7 +15,7 @@
*
*
* @link https://wordpress.org/plugins/woo-retailcrm/
* @version 3.0.0
* @version 3.2.0
*
* @package RetailCRM
*/

View File

@ -13,12 +13,9 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
'p_private' => 'no',
'p_publish' => 'no',
'order_methods' => '',
'flat_rate' => 'delivery',
'flat_rate:1' => 'delivery1',
'free_shipping:7' => 'delivery2',
'flat_rate:8' => 'delivery3',
'local_pickup:9' => 'delivery4',
'flat_rate_shipping' => 'delivery5',
'flat_rate_shipping' => 'delivery',
'free_shipping' => 'delivery2',
'local_pickup' => 'delivery3',
'bacs' => 'payment1',
'cheque' => 'payment2',
'cod' => 'payment3',

View File

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

View File

@ -1,6 +1,6 @@
<?php
class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
class WC_Retailcrm_History_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $apiMock;
protected $responseMockOrderMethods;

View File

@ -0,0 +1,384 @@
<?php
class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $apiMock;
protected $customersHistoryResponse;
protected $ordersHistoryResponse;
const STATUS_1 = 'status1';
const STATUS_2 = 'status4';
public function setUp()
{
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Proxy')
->disableOriginalConstructor()
->setMethods(array(
'ordersHistory',
'customersHistory'
))
->getMock();
$this->customersHistoryResponse = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
$this->ordersHistoryResponse = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(array(
'isSuccessful'
))
->getMock();
parent::setUp();
}
/**
* @dataProvider dataProvider
* @param $api_version
*/
public function test_history_order_create($api_version)
{
$this->setOptions($api_version);
$this->customersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$this->customersHistoryResponse->setResponse(array('success' => true, 'history' => array()));
$this->ordersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$product = WC_Helper_Product::create_simple_product();
$this->ordersHistoryResponse->setResponse(
$this->get_history_data_new_order($product->get_id())
);
$this->apiMock->expects($this->any())->method('customersHistory')->willReturn($this->customersHistoryResponse);
$this->apiMock->expects($this->any())->method('ordersHistory')->willReturn($this->ordersHistoryResponse);
$retailcrm_history = new \WC_Retailcrm_History($this->apiMock);
$retailcrm_history->getHistory();
$orders = wc_get_orders(array('numberposts' => 10));
$order_added = end($orders);
$order_added_items = $order_added->get_items();
$order_added_item = reset($order_added_items);
$shipping_address = $order_added->get_address('shipping');
$billing_address = $order_added->get_address('billing');
$options = get_option(\WC_Retailcrm_Base::$option_key);
$this->assertEquals(self::STATUS_1, $options[$order_added->get_status()]);
$this->assertEquals($product->get_id(), $order_added_item->get_product()->get_id());
$this->assertNotEmpty($shipping_address['first_name']);
$this->assertNotEmpty($shipping_address['last_name']);
$this->assertNotEmpty($shipping_address['postcode']);
$this->assertNotEmpty($shipping_address['city']);
$this->assertNotEmpty($shipping_address['country']);
$this->assertNotEmpty($shipping_address['state']);
$this->assertNotEmpty($billing_address['phone']);
$this->assertNotEmpty($billing_address['email']);
$this->assertNotEmpty($billing_address['first_name']);
$this->assertNotEmpty($billing_address['last_name']);
$this->assertNotEmpty($billing_address['postcode']);
$this->assertNotEmpty($billing_address['city']);
$this->assertNotEmpty($billing_address['country']);
$this->assertNotEmpty($billing_address['state']);
}
/**
* @dataProvider dataProvider
* @param $api_version
*/
public function test_history_order_add_product($api_version)
{
$this->setOptions($api_version);
$this->customersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$this->customersHistoryResponse->setResponse(array('success' => true, 'history' => array()));
$this->ordersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$product = WC_Helper_Product::create_simple_product();
$order = WC_Helper_Order::create_order(0);
$this->ordersHistoryResponse->setResponse(
$this->get_history_data_product_add($product->get_id(), $order->get_id())
);
$this->apiMock->expects($this->any())->method('customersHistory')->willReturn($this->customersHistoryResponse);
$this->apiMock->expects($this->any())->method('ordersHistory')->willReturn($this->ordersHistoryResponse);
$retailcrm_history = new \WC_Retailcrm_History($this->apiMock);
$retailcrm_history->getHistory();
$order_updated = wc_get_order($order->get_id());
$order_updated_items = $order_updated->get_items();
$order_updated_item = end($order_updated_items);
$this->assertEquals(2, count($order_updated_items));
$this->assertEquals(2, $order_updated_item->get_quantity());
$this->assertEquals($product->get_id(), $order_updated_item->get_product()->get_id());
}
/**
* @dataProvider dataProvider
* @param $api_version
*/
public function test_history_order_update_status($api_version)
{
$this->setOptions($api_version);
$this->customersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$this->customersHistoryResponse->setResponse(array('success' => true, 'history' => array()));
$this->ordersHistoryResponse->expects($this->any())
->method('isSuccessful')
->willReturn(true);
$order = WC_Helper_Order::create_order(0);
$this->ordersHistoryResponse->setResponse(
$this->get_history_data_status_update($order->get_id())
);
$this->apiMock->expects($this->any())->method('customersHistory')->willReturn($this->customersHistoryResponse);
$this->apiMock->expects($this->any())->method('ordersHistory')->willReturn($this->ordersHistoryResponse);
$retailcrm_history = new \WC_Retailcrm_History($this->apiMock);
$retailcrm_history->getHistory();
$order_updated = wc_get_order($order->get_id());
$options = get_option(\WC_Retailcrm_Base::$option_key);
$this->assertEquals(self::STATUS_2, $options[$order_updated->get_status()]);
}
public function dataProvider()
{
return array(
array(
'api_version' => 'v4'
),
array(
'api_version' => 'v5'
)
);
}
private function get_history_data_new_order($product_create_id)
{
return array(
'success' => true,
'history' => array(
array(
'id' => 1,
'createdAt' => '2018-01-01 00:00:00',
'created' => true,
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'status',
'oldValue' => null,
'newValue' => array(
'code' => self::STATUS_1
),
'order' => array(
'slug' => 1,
'id' => 1,
'number' => '1C',
'orderType' => 'eshop-individual',
'orderMethod' => 'phone',
'countryIso' => 'RU',
'createdAt' => '2018-01-01 00:00:00',
'statusUpdatedAt' => '2018-01-01 00:00:00',
'summ' => 100,
'totalSumm' => 100,
'prepaySum' => 0,
'purchaseSumm' => 50,
'markDatetime' => '2018-01-01 00:00:00',
'firstName' => 'Test',
'lastName' => 'Test',
'phone' => '80000000000',
'call' => false,
'expired' => false,
'customer' => array(
'segments' => array(),
'id' => 1,
'firstName' => 'Test',
'lastName' => 'Test',
'email' => 'email@test.ru',
'phones' => array(
array(
'number' => '111111111111111'
),
array(
'number' => '+7111111111'
)
),
'address' => array(
'index' => '111111',
'countryIso' => 'RU',
'region' => 'Test region',
'city' => 'Test',
'text' => 'Test text address'
),
'createdAt' => '2018-01-01 00:00:00',
'managerId' => 1,
'vip' => false,
'bad' => false,
'site' => 'test-com',
'contragent' => array(
'contragentType' => 'individual'
),
'personalDiscount' => 0,
'cumulativeDiscount' => 0,
'marginSumm' => 58654,
'totalSumm' => 61549,
'averageSumm' => 15387.25,
'ordersCount' => 4,
'costSumm' => 101,
'customFields' => array(
'custom' => 'test'
)
),
'contragent' => array(),
'delivery' => array(
'cost' => 0,
'netCost' => 0,
'address' => array(
'index' => '111111',
'countryIso' => 'RU',
'region' => 'Test region',
'city' => 'Test',
'text' => 'Test text address'
)
),
'site' => 'test-com',
'status' => self::STATUS_1,
'items' => array(
array(
'id' => 160,
'initialPrice' => 100,
'createdAt' => '2018-01-01 00:00:00',
'quantity' => 1,
'status' => 'new',
'offer' => array(
'id' => 1,
'externalId' => $product_create_id,
'xmlId' => '1',
'name' => 'Test name',
'vatRate' => 'none'
),
'properties' => array(),
'purchasePrice' => 50
)
),
'fromApi' => false,
'length' => 0,
'width' => 0,
'height' => 0,
'shipmentStore' => 'main',
'shipped' => false,
'customFields' => array(),
'uploadedToExternalStoreSystem' => false
)
)
)
);
}
private function get_history_data_product_add($product_add_id, $order_id)
{
return array(
'success' => true,
'history' => array(
array(
'id' => 2,
'createdAt' => '2018-01-01 00:00:01',
'source'=> 'user',
'user' => array(
'id'=> 1
),
'field' => 'order_product',
'oldValue' => null,
'newValue' => array(
'id' => 2,
'offer' => array(
'id'=> 2,
'externalId' => $product_add_id,
'xmlId' => 'xmlId'
)
),
'order' => array(
'id' => 2,
'externalId' => $order_id,
'site' => 'test-com',
'status' => self::STATUS_1
),
'item' => array(
'id' => 2,
'initialPrice' => 999,
'createdAt' => '2018-01-01 00:02:00',
'quantity' => 2,
'status' => self::STATUS_1,
'offer' => array(
'id' => 2,
'externalId' => $product_add_id,
'xmlId' => 'xmlId',
'name' => 'Test name 2'
),
'properties' => array(),
'purchasePrice' => 500
)
)
)
);
}
private function get_history_data_status_update($order_id)
{
return array(
'success' => true,
'history' => array(
array(
'id' => 3,
'createdAt' => '2018-01-01 00:03:00',
'source' => 'user',
'user' => array(
'id' => 1
),
'field' => 'status',
'oldValue' => array(
'code' => 'new'
),
'newValue' => array(
'code' => self::STATUS_2
),
'order' => array(
'id' => 2,
'externalId' => $order_id,
'managerId' => 6,
'site' => 'test-com',
'status' => self::STATUS_2
)
)
)
);
}
}

View File

@ -3,7 +3,6 @@
class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $apiMock;
protected $responseMock;
protected $order;
protected $options;
@ -78,7 +77,7 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertEquals('US', $order_send['countryIso']);
$this->assertEquals('123456', $order_send['delivery']['address']['index']);
$this->assertEquals('WooCity', $order_send['delivery']['address']['city']);
$this->assertEquals('delivery5', $order_send['delivery']['code']);
$this->assertEquals('delivery', $order_send['delivery']['code']);
if ($apiVersion == 'v4') {
$this->assertArrayHasKey('paymentType', $order_send);
@ -158,7 +157,7 @@ class WC_Retailcrm_Orders_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertEquals('US', $order_send['countryIso']);
$this->assertEquals('123456', $order_send['delivery']['address']['index']);
$this->assertEquals('WooCity', $order_send['delivery']['address']['city']);
$this->assertEquals('delivery5', $order_send['delivery']['code']);
$this->assertEquals('delivery', $order_send['delivery']['code']);
if ($apiVersion == 'v4') {
$this->assertArrayHasKey('paymentType', $order_send);