⚡ NEW: Changeset/ - Full Archive

Changeset 3077704


Ignore:
Timestamp:
04/26/2024 03:00:24 PM (20 months ago)
Author:
redmonkey73
Message:

Update to version 2.12 from GitHub

Location:
bonus-plus-wp
Files:
8 added
20 edited
1 copied

Legend:

Unmodified
Added
Removed
  • bonus-plus-wp/tags/2.12/assets/customer.js

    r3043418 r3077704  
    191191                document.getElementById('bpmsg').innerHTML = 'Списание бонусов';
    192192                show(document.getElementById('bpmsg'));
    193                 jQuery('body').trigger('update_checkout');
     193               
     194                jQuery.ajax({
     195                    type: "post",
     196                    url:  wc_checkout_params.ajax_url,
     197                    data: {
     198                        'action' : 'set_bpwp_debit_bonuses',
     199                        'bonuses' : response.debit_bonuses
     200                    },
     201                    success: function(response) {
     202                        jQuery('body').trigger('update_checkout');
     203                    },
     204                    error: function(error){
     205                        console.log('error: '+error);
     206                    }
     207                });
     208
    194209            } else {
    195210                document.getElementById('bpmsg').innerHTML = 'Код не верный, попробуйте еще раз';
  • bonus-plus-wp/tags/2.12/bonus-plus-wp.php

    r3043418 r3077704  
    1515 * WP requires at least: 6.0
    1616 * Tested up to: 6.4.2
    17  * Version: 2.11
     17 * Version: 2.12
    1818 */
    1919namespace BPWP;
     
    2828    public static function init()
    2929    {
    30         define('BPWP_PLUGIN_VERSION', '2.11');
     30        define('BPWP_PLUGIN_VERSION', '2.12');
     31
     32        define('BPWP_PLUGIN_DIR', plugin_dir_path(__FILE__));
    3133
    3234        require_once __DIR__ . '/functions.php';
    3335
    34         if ( ! session_id() && ! headers_sent() ) {
    35             session_start();
    36         }
    3736        /**
    3837         * Add hook for activate plugin
     
    5352
    5453        add_action('wp_enqueue_scripts', [__CLASS__, 'bpwp_shortcode_wp_enqueue_styles']);
     54
    5555    }
    56 
     56   
    5757    /**
    5858     * Add languages
     
    7373    {
    7474        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
     75            require_once __DIR__ . '/inc/RestApiEndpoints.php';
    7576            require_once __DIR__ . '/inc/WooAccount.php';
    7677            require_once __DIR__ . '/inc/ApiHelper.php';
     
    8182        require_once __DIR__ . '/inc/WooProductCatExport.php';
    8283        require_once __DIR__ . '/inc/CustomerBalance.php';
    83         require_once __DIR__ . '/inc/RestApiEndpoints.php';
    8484    }   
    8585
     
    101101            'bpwp-bonus-loader-style',
    102102            plugins_url('/assets/loader.css', __FILE__),
     103            [],
     104            BPWP_PLUGIN_VERSION,
     105            'all'
     106        );
     107        wp_register_style(
     108            'bpwp-user-qr-card-style',
     109            plugins_url('/assets/qrcard.css', __FILE__),
    103110            [],
    104111            BPWP_PLUGIN_VERSION,
  • bonus-plus-wp/tags/2.12/functions.php

    r3033150 r3077704  
    161161    return $code && key_exists($code, $errors) ? $errors[$code] : false;
    162162}
     163
     164// Запишем bpwp_debit_bonuses в WC()->session
     165add_action( 'wp_ajax_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
     166add_action( 'wp_ajax_nopriv_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
     167function set_bpwp_debit_bonuses() {
     168   
     169    if (!is_user_logged_in()) {
     170        return;
     171    }
     172   
     173    $bonuses = get_user_meta(get_current_user_id(), 'bpwp_debit_bonuses', true);
     174   
     175    if( true == $_POST['bonuses'] && isset($bonuses) && isset($bonuses) > 0 ){
     176        delete_user_meta(get_current_user_id(), 'bpwp_debit_bonuses');
     177        WC()->session->set( 'bpwp_debit_bonuses', $bonuses );
     178        echo true;
     179    }
     180    exit();
     181}
  • bonus-plus-wp/tags/2.12/inc/ApiHelper.php

    r3043418 r3077704  
    22
    33namespace BPWP;
    4 
    5 use WC_Cart;
    64
    75defined('ABSPATH') || exit; // Exit if accessed directly
     
    2119        add_action('woocommerce_checkout_before_order_review', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    2220        add_action('woocommerce_product_meta_end', [__CLASS__, 'bpwp_single_bonusplus_price'], 10);
    23         add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'bpwp_add_custom_fee_on_checkout']);
     21        add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'bpwp_add_custom_fee_on_checkout'], 20, 1);
    2422
    2523        add_action( 'woocommerce_add_to_cart', [__CLASS__, 'bpwp_cart_updated' ] );
    2624        add_action( 'woocommerce_update_cart_action_cart_updated', [__CLASS__, 'bpwp_cart_updated' ] );
    27 
    28     }
    29 
    30     public static function bpwp_add_custom_fee_on_checkout(WC_Cart $cart)
    31     {
    32         // Получить данные для списания бонусов
    33         $fee_amount = -(int)$_SESSION['bpwp_debit_bonuses'];
    34         $fee_name = apply_filters('bpwp_order_fee_name', 'Списание бонусов');
    35         $taxable = true;
    36         $tax_class = 'bpwp-bonuses-reserved';
    37        
    38         if ( ! empty( $fee_amount ) ) {
    39             $cart->add_fee($fee_name, $fee_amount, $taxable, $tax_class);
     25    }
     26   
     27    // Списание бонусов в заказе
     28    public static function bpwp_add_custom_fee_on_checkout($cart)
     29    {
     30        if (WC()->session->__isset('bpwp_debit_bonuses')) {
     31            $discount = (float) WC()->session->get('bpwp_debit_bonuses');
     32        }
     33       
     34        if (isset($discount) && $discount > 0) {
     35        $cart->add_fee(__('Списание бонусов', 'bonus-plus-wp'), -$discount);
    4036        }
    4137    }
    4238   
    4339    public static function bpwp_cart_updated($cart_updated) {
    44         $_SESSION['bpwp_debit_bonuses'] = 0;
     40        if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     41            WC()->session->set('bpwp_debit_bonuses', null);
     42        }
     43        delete_user_meta(get_current_user_id(), 'bpwp_debit_bonuses');
    4544        return true;
    4645    }
  • bonus-plus-wp/tags/2.12/inc/ClientProfile.php

    r3043418 r3077704  
    4444
    4545        wp_enqueue_style('bpwp-bonus-card-style');
    46 
     46        wp_enqueue_style('bpwp-user-qr-card-style');
    4747        ob_start(); ?>
    4848
     
    137137            $data['class']  =   'card3';
    138138
    139             // Проверим заполнены ли у порльзователя дата рождения и телефон
     139            // Проверим заполнены ли у пользователя платежный телефон
    140140            $user_id = get_current_user_id();
    141141            $billing_phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
     
    183183        $phone = bpwp_api_get_customer_phone($user_id);
    184184        // Если у пользователя есть мета bonus-plus, значит телефон ранее верифицирован
    185         // if (!empty(get_user_meta($user_id, 'bonus-plus', true))){
    186             // Значит обновим данные
    187             //$phone = bpwp_api_get_customer_phone($user_id);
    188             //$isPhoneVerified = get_user_meta($user_id, 'bpwp_phone_verified', true);
    189             if (!empty($phone)) {
    190                 $res = bpwp_api_request(
    191                     'customer',
    192                     array(
    193                         'phone' => $phone
    194                     ),
    195                     'GET'
    196                 );
    197                 if ($res['code'] == 200){
    198                     update_user_meta($user_id, 'bonus-plus', $res['request']);
    199                 } else {
    200                     do_action(
    201                         'bpwp_logger',
    202                         $type = __CLASS__,
    203                         /* translators: Error message when retrieving customer data. %s is the user ID. */
    204                         $title = __('Ошибка при получении данных клиента', 'bonus-plus-wp'),
    205                         /* translators: %s is the user ID. */
    206                         $desc = sprintf(__('У пользователя с ИД %s, данные не получены!', 'bonus-plus-wp'), $user_id),
    207                     );
    208                 }
    209                
    210             } else { 
     185        // Значит обновим данные
     186        if (!empty($phone)) {
     187            $res = bpwp_api_request(
     188                'customer',
     189                array(
     190                    'phone' => $phone
     191                ),
     192                'GET'
     193            );
     194            if ($res['code'] == 200){
     195                update_user_meta($user_id, 'bonus-plus', $res['request']);
     196            } else {
    211197                do_action(
    212198                    'bpwp_logger',
    213199                    $type = __CLASS__,
    214                     /* translators: Message displayed when phone is not verified. */
    215                     $title = __('Не верифицирован телефон', 'bonus-plus-wp'),
    216                     /* translators: Message displayed when phone is not verified. %s is the user ID. */
    217                     $desc = sprintf(__('У пользователя с ИД %s не верифицирован телефон, данные не получены!', 'bonus-plus-wp'), $user_id),
    218                 );
    219             }
    220         //}   
     200                    /* translators: Error message when retrieving customer data. %s is the user ID. */
     201                    $title = __('Ошибка при получении данных клиента', 'bonus-plus-wp'),
     202                    /* translators: %s is the user ID. */
     203                    $desc = sprintf(__('У пользователя с ИД %s, данные не получены!', 'bonus-plus-wp'), $user_id),
     204                );
     205            }
     206               
     207        } else { 
     208            do_action(
     209                'bpwp_logger',
     210                $type = __CLASS__,
     211                /* translators: Message displayed when phone is not verified. */
     212                $title = __('Не верифицирован телефон', 'bonus-plus-wp'),
     213                /* translators: Message displayed when phone is not verified. %s is the user ID. */
     214                $desc = sprintf(__('У пользователя с ИД %s не верифицирован телефон, данные не получены!', 'bonus-plus-wp'), $user_id),
     215            );
     216        } 
    221217    }
    222218
  • bonus-plus-wp/tags/2.12/inc/CustomerBalance.php

    r3043418 r3077704  
    1313    {
    1414        // Создание заказа - Резервирование бонусов на счету клиента
    15         add_action( 'woocommerce_new_order', [__CLASS__, 'bpwp_balance_reserve_bonusplus'], 10, 2 );
     15        // Добавление данных из мета корзины в мета данные заказа
     16        add_action( 'woocommerce_new_order', [__CLASS__, 'bpwp_balance_reserve_bonusplus'], 90, 2 );
    1617
    1718        // Заказ выполнен, запрос с начислением бонусов. Комментарий в заказ - "бонусы начисены"
    1819        add_action( 'woocommerce_order_status_completed', [__CLASS__, 'bpwp_customer_balance_bonusplus'] );
    19         add_action( 'woocommerce_cancelled_order', [__CLASS__,'bpwp_cancelled_order'] ); // Заказ отменен
     20        add_action( 'woocommerce_order_status_cancelled', [__CLASS__,'bpwp_cancelled_order'] ); // Заказ отменен
    2021    }
    2122
     
    4243           
    4344            // Освобождаем из резерва, передаем отрицательное число
    44             self::bpwp_balance_reserve($order_data);
    45         }
    46     }
    47 
     45            $balance_reserve = self::bpwp_balance_reserve($order_data);
     46            if ($balance_reserve['code'] == 204) {
     47                delete_post_meta( $order_id, '_bonus_debit');
     48            }
     49        }
     50    }
    4851
    4952    /**
     
    5255    public static function bpwp_balance_reserve_bonusplus($order_id, $order)
    5356    {
    54         // Добавить в мета значение из $_SESSION['bpwp_debit_bonuses']
    55         $bonus_debit = $_SESSION['bpwp_debit_bonuses'];
     57        if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     58            $bonus_debit = WC()->session->get('bpwp_debit_bonuses');
     59        } else {
     60            return;
     61        }
     62
    5663        $user_id = $order->get_user_id();
    5764       
     
    6673        */
    6774        $balance_reserve = self::bpwp_balance_reserve($order_data);
    68 
     75       
    6976        if ($balance_reserve['code'] == 204) {
    7077           
     
    7380            if ($info && is_array($info)) {
    7481                $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
    75                
    7682                update_user_meta($user_id, 'bonus-plus', $info);
    7783            }
    78 
     84           
    7985            // Добавить бонусы в мета заказа
    8086            add_post_meta( $order_id, '_bonus_debit', $bonus_debit, true);
     87
     88            if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     89                WC()->session->set('bpwp_debit_bonuses', null);
     90            }
    8191       
    8292        } else {
     
    121131        $user_id = $order->get_user_id();
    122132        $bonus_debit = $order->get_meta( '_bonus_debit' );
    123        
     133
    124134        if (isset($bonus_debit) || !empty($bonus_debit)) {
    125135           
     
    129139                'bonus_debit' => -(int)$bonus_debit,
    130140            );
    131            
     141
    132142            // Освобождаем из резерва, передаем отрицательное число
    133143            $balance_reserve = self::bpwp_balance_reserve($order_data);
     
    146156                    $type = __CLASS__,
    147157                    $title = __('Проведение продажи в БонусПлюс', 'bonus-plus-wp'),
    148                     $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id,),
     158                    $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id),
    149159                    );
    150160                }
  • bonus-plus-wp/tags/2.12/inc/RestApiEndpoints.php

    r3043418 r3077704  
    1313    {
    1414        add_action('rest_api_init', [$this, 'register_endpoints'], 10);
     15        // Early enable customer WC_Session
     16        //add_action( 'init', [$this,'wc_session_enabler'] ); //https://rajaamanullah.com/how-to-use-woocommerce-sessions-and-cookies/
     17    }
     18   
     19    public static function wc_session_enabler() {
     20        if ( is_user_logged_in() || is_admin() )
     21            return;
     22   
     23        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
     24            WC()->session->set_customer_session_cookie( true );
     25        }
    1526    }
    1627
     
    131142            );
    132143           
    133             // *! Добавить Fee
     144            // *! Передаем количество бонусов
    134145            if ($args['debit'] > 0) {
    135146               
    136                 $_SESSION['bpwp_debit_bonuses'] = (int)$args['debit'];
    137                
     147                update_user_meta($user_id, 'bpwp_debit_bonuses', esc_attr($args['debit']));
     148
    138149                $response = array(
    139150                    'success' => true,
     
    145156                wp_die();
    146157            }
    147            
     158
    148159            // Код верный. Запрос проверки существования пользвателя в б+
    149160            $get_customer = bpwp_api_request(
  • bonus-plus-wp/tags/2.12/inc/WooAccount.php

    r3043418 r3077704  
    9898        if ($info && is_array($info)) {
    9999
    100             printf('<h2>%s</h2>', 'Информация по карте лояльности');
    101             echo '<div id="loader" class="center-body"><div class="loader-ball-8"></div></div>';
    102             //do_action('bpwp_after_bonus_card_info_title');
    103             echo '<br><div id="qrcode"></div><br>';
    104 
    105100            foreach ($info as $key => $value) {
    106101                if ($key != 'person') {
    107102                    if ($key == 'discountCardName') {
    108                         printf('%s:%s<br />', esc_html(__('Тип карты', 'bonus-plus-wp')), esc_html($value));
     103                        $discountCardName = $value;
     104                        //printf('%s:%s<br />', esc_html(__('Тип карты', 'bonus-plus-wp')), esc_html($value));
    109105                    }
    110106                    if ($key == 'discountCardNumber') {
    111                         printf('%s:%s<br />', esc_html(__('Номер карты', 'bonus-plus-wp')), esc_html($value));
     107                        $discountCardNumber = $value;
     108                        //printf('%s:%s<br />', esc_html(__('Номер карты', 'bonus-plus-wp')), esc_html($value));
    112109                    }
    113110                    if ($key == 'availableBonuses') {
    114                         printf('%s:%s<br />', esc_html(__('Доступных бонусов', 'bonus-plus-wp')), esc_html($value));
     111                        $availableBonuses = $value;
     112                        //printf('%s:%s<br />', esc_html(__('Доступных бонусов', 'bonus-plus-wp')), esc_html($value));
    115113                    }
    116114                    if ($key == 'notActiveBonuses') {
    117                         printf('%s:%s<br />', esc_html(__('Неактивных бонусов', 'bonus-plus-wp')), esc_html($value));
     115                        //printf('%s:%s<br />', esc_html(__('Неактивных бонусов', 'bonus-plus-wp')), esc_html($value));
    118116                    }
    119117                    if ($key == 'purchasesTotalSum') {
    120                         printf('%s:%s<br />', esc_html(__('Сумма покупок', 'bonus-plus-wp')), esc_html($value));
     118                        $purchasesTotalSum = $value;
     119                        //printf('%s:%s<br />', esc_html(__('Сумма покупок', 'bonus-plus-wp')), esc_html($value));
    121120                    }
    122121                    if ($key == 'purchasesSumToNextCard') {
    123                         printf('%s:%s<br />', esc_html(__('Сумма покупок для смены карты', 'bonus-plus-wp')), esc_html($value));
     122                        $purchasesSumToNextCard = $value;
     123                        //printf('%s:%s<br />', esc_html(__('Сумма покупок для смены карты', 'bonus-plus-wp')), esc_html($value));
    124124                    }
    125125                    if ($key == 'lastPurchaseDate') {
    126                         printf('%s:%s<br />', esc_html(__('Последняя покупка', 'bonus-plus-wp')), esc_html($value));
     126                        //printf('%s:%s<br />', esc_html(__('Последняя покупка', 'bonus-plus-wp')), esc_html($value));
    127127                    }
    128128                } else {
     
    140140                        }
    141141                    }
    142                     }
    143142                }
    144 
     143            }
     144        include_once(BPWP_PLUGIN_DIR . 'templates/client-card.php');
    145145        } else { // нет данных в бонус+
    146146            do_action('bpwp_veryfy_client_data');
     
    191191        );
    192192        wp_enqueue_style('bpwp-bonus-loader-style');
     193        wp_enqueue_style('bpwp-user-qr-card-style');
    193194    }
    194195
  • bonus-plus-wp/tags/2.12/inc/WooProductCatExport.php

    r3033150 r3077704  
    295295                $type = __CLASS__,
    296296                $title = __('Экспорт товаров в Бонус+, невозможен', 'bonus-plus-wp'),
    297                 $desc = __('Параметры название магазина или список продуктовпереданы неверно', 'bonus-plus-wp'),
     297                $desc = __('Параметры название магазина или список продуктов переданы неверно', 'bonus-plus-wp'),
    298298            );
    299299        }
  • bonus-plus-wp/tags/2.12/readme.txt

    r3043418 r3077704  
    11=== WPBonusPlus ===
    2 Contributors: redmonkey73
     2Contributors: redmonkey73, mickuznetsov
    33Donate link: https://github.com/evgrezanov
    44Tags: bonus, woocommerce, sync, integration
    55Requires at least: 4.0
    6 Tested up to: 6.4.2
    7 Stable tag: 2.11
     6Tested up to: 6.5
     7Stable tag: 2.12
    88Requires PHP: 8.1
    99License: GPLv2 or later
     
    9393== Changelog ==
    9494
    95 = 2.11=
     95= 2.12 =
     96- fix bugs
     97- Вынести шаблон карты в лк в /templates
     98
     99= 2.11 =
    96100- возможность списания части бонусов на чекауте https://github.com/evgrezanov/bonus-plus-wp/issues/63
    97101- bugs fixing
  • bonus-plus-wp/trunk/assets/customer.js

    r3043418 r3077704  
    191191                document.getElementById('bpmsg').innerHTML = 'Списание бонусов';
    192192                show(document.getElementById('bpmsg'));
    193                 jQuery('body').trigger('update_checkout');
     193               
     194                jQuery.ajax({
     195                    type: "post",
     196                    url:  wc_checkout_params.ajax_url,
     197                    data: {
     198                        'action' : 'set_bpwp_debit_bonuses',
     199                        'bonuses' : response.debit_bonuses
     200                    },
     201                    success: function(response) {
     202                        jQuery('body').trigger('update_checkout');
     203                    },
     204                    error: function(error){
     205                        console.log('error: '+error);
     206                    }
     207                });
     208
    194209            } else {
    195210                document.getElementById('bpmsg').innerHTML = 'Код не верный, попробуйте еще раз';
  • bonus-plus-wp/trunk/bonus-plus-wp.php

    r3043418 r3077704  
    1515 * WP requires at least: 6.0
    1616 * Tested up to: 6.4.2
    17  * Version: 2.11
     17 * Version: 2.12
    1818 */
    1919namespace BPWP;
     
    2828    public static function init()
    2929    {
    30         define('BPWP_PLUGIN_VERSION', '2.11');
     30        define('BPWP_PLUGIN_VERSION', '2.12');
     31
     32        define('BPWP_PLUGIN_DIR', plugin_dir_path(__FILE__));
    3133
    3234        require_once __DIR__ . '/functions.php';
    3335
    34         if ( ! session_id() && ! headers_sent() ) {
    35             session_start();
    36         }
    3736        /**
    3837         * Add hook for activate plugin
     
    5352
    5453        add_action('wp_enqueue_scripts', [__CLASS__, 'bpwp_shortcode_wp_enqueue_styles']);
     54
    5555    }
    56 
     56   
    5757    /**
    5858     * Add languages
     
    7373    {
    7474        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
     75            require_once __DIR__ . '/inc/RestApiEndpoints.php';
    7576            require_once __DIR__ . '/inc/WooAccount.php';
    7677            require_once __DIR__ . '/inc/ApiHelper.php';
     
    8182        require_once __DIR__ . '/inc/WooProductCatExport.php';
    8283        require_once __DIR__ . '/inc/CustomerBalance.php';
    83         require_once __DIR__ . '/inc/RestApiEndpoints.php';
    8484    }   
    8585
     
    101101            'bpwp-bonus-loader-style',
    102102            plugins_url('/assets/loader.css', __FILE__),
     103            [],
     104            BPWP_PLUGIN_VERSION,
     105            'all'
     106        );
     107        wp_register_style(
     108            'bpwp-user-qr-card-style',
     109            plugins_url('/assets/qrcard.css', __FILE__),
    103110            [],
    104111            BPWP_PLUGIN_VERSION,
  • bonus-plus-wp/trunk/functions.php

    r3033150 r3077704  
    161161    return $code && key_exists($code, $errors) ? $errors[$code] : false;
    162162}
     163
     164// Запишем bpwp_debit_bonuses в WC()->session
     165add_action( 'wp_ajax_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
     166add_action( 'wp_ajax_nopriv_set_bpwp_debit_bonuses', 'set_bpwp_debit_bonuses' );
     167function set_bpwp_debit_bonuses() {
     168   
     169    if (!is_user_logged_in()) {
     170        return;
     171    }
     172   
     173    $bonuses = get_user_meta(get_current_user_id(), 'bpwp_debit_bonuses', true);
     174   
     175    if( true == $_POST['bonuses'] && isset($bonuses) && isset($bonuses) > 0 ){
     176        delete_user_meta(get_current_user_id(), 'bpwp_debit_bonuses');
     177        WC()->session->set( 'bpwp_debit_bonuses', $bonuses );
     178        echo true;
     179    }
     180    exit();
     181}
  • bonus-plus-wp/trunk/inc/ApiHelper.php

    r3043418 r3077704  
    22
    33namespace BPWP;
    4 
    5 use WC_Cart;
    64
    75defined('ABSPATH') || exit; // Exit if accessed directly
     
    2119        add_action('woocommerce_checkout_before_order_review', [__CLASS__, 'bpwp_cart_checkout_bonusplus_price']);
    2220        add_action('woocommerce_product_meta_end', [__CLASS__, 'bpwp_single_bonusplus_price'], 10);
    23         add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'bpwp_add_custom_fee_on_checkout']);
     21        add_action('woocommerce_cart_calculate_fees', [__CLASS__, 'bpwp_add_custom_fee_on_checkout'], 20, 1);
    2422
    2523        add_action( 'woocommerce_add_to_cart', [__CLASS__, 'bpwp_cart_updated' ] );
    2624        add_action( 'woocommerce_update_cart_action_cart_updated', [__CLASS__, 'bpwp_cart_updated' ] );
    27 
    28     }
    29 
    30     public static function bpwp_add_custom_fee_on_checkout(WC_Cart $cart)
    31     {
    32         // Получить данные для списания бонусов
    33         $fee_amount = -(int)$_SESSION['bpwp_debit_bonuses'];
    34         $fee_name = apply_filters('bpwp_order_fee_name', 'Списание бонусов');
    35         $taxable = true;
    36         $tax_class = 'bpwp-bonuses-reserved';
    37        
    38         if ( ! empty( $fee_amount ) ) {
    39             $cart->add_fee($fee_name, $fee_amount, $taxable, $tax_class);
     25    }
     26   
     27    // Списание бонусов в заказе
     28    public static function bpwp_add_custom_fee_on_checkout($cart)
     29    {
     30        if (WC()->session->__isset('bpwp_debit_bonuses')) {
     31            $discount = (float) WC()->session->get('bpwp_debit_bonuses');
     32        }
     33       
     34        if (isset($discount) && $discount > 0) {
     35        $cart->add_fee(__('Списание бонусов', 'bonus-plus-wp'), -$discount);
    4036        }
    4137    }
    4238   
    4339    public static function bpwp_cart_updated($cart_updated) {
    44         $_SESSION['bpwp_debit_bonuses'] = 0;
     40        if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     41            WC()->session->set('bpwp_debit_bonuses', null);
     42        }
     43        delete_user_meta(get_current_user_id(), 'bpwp_debit_bonuses');
    4544        return true;
    4645    }
  • bonus-plus-wp/trunk/inc/ClientProfile.php

    r3043418 r3077704  
    4444
    4545        wp_enqueue_style('bpwp-bonus-card-style');
    46 
     46        wp_enqueue_style('bpwp-user-qr-card-style');
    4747        ob_start(); ?>
    4848
     
    137137            $data['class']  =   'card3';
    138138
    139             // Проверим заполнены ли у порльзователя дата рождения и телефон
     139            // Проверим заполнены ли у пользователя платежный телефон
    140140            $user_id = get_current_user_id();
    141141            $billing_phone = get_user_meta(get_current_user_id(), 'billing_phone', true);
     
    183183        $phone = bpwp_api_get_customer_phone($user_id);
    184184        // Если у пользователя есть мета bonus-plus, значит телефон ранее верифицирован
    185         // if (!empty(get_user_meta($user_id, 'bonus-plus', true))){
    186             // Значит обновим данные
    187             //$phone = bpwp_api_get_customer_phone($user_id);
    188             //$isPhoneVerified = get_user_meta($user_id, 'bpwp_phone_verified', true);
    189             if (!empty($phone)) {
    190                 $res = bpwp_api_request(
    191                     'customer',
    192                     array(
    193                         'phone' => $phone
    194                     ),
    195                     'GET'
    196                 );
    197                 if ($res['code'] == 200){
    198                     update_user_meta($user_id, 'bonus-plus', $res['request']);
    199                 } else {
    200                     do_action(
    201                         'bpwp_logger',
    202                         $type = __CLASS__,
    203                         /* translators: Error message when retrieving customer data. %s is the user ID. */
    204                         $title = __('Ошибка при получении данных клиента', 'bonus-plus-wp'),
    205                         /* translators: %s is the user ID. */
    206                         $desc = sprintf(__('У пользователя с ИД %s, данные не получены!', 'bonus-plus-wp'), $user_id),
    207                     );
    208                 }
    209                
    210             } else { 
     185        // Значит обновим данные
     186        if (!empty($phone)) {
     187            $res = bpwp_api_request(
     188                'customer',
     189                array(
     190                    'phone' => $phone
     191                ),
     192                'GET'
     193            );
     194            if ($res['code'] == 200){
     195                update_user_meta($user_id, 'bonus-plus', $res['request']);
     196            } else {
    211197                do_action(
    212198                    'bpwp_logger',
    213199                    $type = __CLASS__,
    214                     /* translators: Message displayed when phone is not verified. */
    215                     $title = __('Не верифицирован телефон', 'bonus-plus-wp'),
    216                     /* translators: Message displayed when phone is not verified. %s is the user ID. */
    217                     $desc = sprintf(__('У пользователя с ИД %s не верифицирован телефон, данные не получены!', 'bonus-plus-wp'), $user_id),
    218                 );
    219             }
    220         //}   
     200                    /* translators: Error message when retrieving customer data. %s is the user ID. */
     201                    $title = __('Ошибка при получении данных клиента', 'bonus-plus-wp'),
     202                    /* translators: %s is the user ID. */
     203                    $desc = sprintf(__('У пользователя с ИД %s, данные не получены!', 'bonus-plus-wp'), $user_id),
     204                );
     205            }
     206               
     207        } else { 
     208            do_action(
     209                'bpwp_logger',
     210                $type = __CLASS__,
     211                /* translators: Message displayed when phone is not verified. */
     212                $title = __('Не верифицирован телефон', 'bonus-plus-wp'),
     213                /* translators: Message displayed when phone is not verified. %s is the user ID. */
     214                $desc = sprintf(__('У пользователя с ИД %s не верифицирован телефон, данные не получены!', 'bonus-plus-wp'), $user_id),
     215            );
     216        } 
    221217    }
    222218
  • bonus-plus-wp/trunk/inc/CustomerBalance.php

    r3043418 r3077704  
    1313    {
    1414        // Создание заказа - Резервирование бонусов на счету клиента
    15         add_action( 'woocommerce_new_order', [__CLASS__, 'bpwp_balance_reserve_bonusplus'], 10, 2 );
     15        // Добавление данных из мета корзины в мета данные заказа
     16        add_action( 'woocommerce_new_order', [__CLASS__, 'bpwp_balance_reserve_bonusplus'], 90, 2 );
    1617
    1718        // Заказ выполнен, запрос с начислением бонусов. Комментарий в заказ - "бонусы начисены"
    1819        add_action( 'woocommerce_order_status_completed', [__CLASS__, 'bpwp_customer_balance_bonusplus'] );
    19         add_action( 'woocommerce_cancelled_order', [__CLASS__,'bpwp_cancelled_order'] ); // Заказ отменен
     20        add_action( 'woocommerce_order_status_cancelled', [__CLASS__,'bpwp_cancelled_order'] ); // Заказ отменен
    2021    }
    2122
     
    4243           
    4344            // Освобождаем из резерва, передаем отрицательное число
    44             self::bpwp_balance_reserve($order_data);
    45         }
    46     }
    47 
     45            $balance_reserve = self::bpwp_balance_reserve($order_data);
     46            if ($balance_reserve['code'] == 204) {
     47                delete_post_meta( $order_id, '_bonus_debit');
     48            }
     49        }
     50    }
    4851
    4952    /**
     
    5255    public static function bpwp_balance_reserve_bonusplus($order_id, $order)
    5356    {
    54         // Добавить в мета значение из $_SESSION['bpwp_debit_bonuses']
    55         $bonus_debit = $_SESSION['bpwp_debit_bonuses'];
     57        if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     58            $bonus_debit = WC()->session->get('bpwp_debit_bonuses');
     59        } else {
     60            return;
     61        }
     62
    5663        $user_id = $order->get_user_id();
    5764       
     
    6673        */
    6774        $balance_reserve = self::bpwp_balance_reserve($order_data);
    68 
     75       
    6976        if ($balance_reserve['code'] == 204) {
    7077           
     
    7380            if ($info && is_array($info)) {
    7481                $info['availableBonuses'] = $info['availableBonuses'] - $bonus_debit;
    75                
    7682                update_user_meta($user_id, 'bonus-plus', $info);
    7783            }
    78 
     84           
    7985            // Добавить бонусы в мета заказа
    8086            add_post_meta( $order_id, '_bonus_debit', $bonus_debit, true);
     87
     88            if (  WC()->session->__isset( 'bpwp_debit_bonuses' ) ) {
     89                WC()->session->set('bpwp_debit_bonuses', null);
     90            }
    8191       
    8292        } else {
     
    121131        $user_id = $order->get_user_id();
    122132        $bonus_debit = $order->get_meta( '_bonus_debit' );
    123        
     133
    124134        if (isset($bonus_debit) || !empty($bonus_debit)) {
    125135           
     
    129139                'bonus_debit' => -(int)$bonus_debit,
    130140            );
    131            
     141
    132142            // Освобождаем из резерва, передаем отрицательное число
    133143            $balance_reserve = self::bpwp_balance_reserve($order_data);
     
    146156                    $type = __CLASS__,
    147157                    $title = __('Проведение продажи в БонусПлюс', 'bonus-plus-wp'),
    148                     $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id,),
     158                    $desc = sprintf(__('Заказа ИД %s, код ошибки %s', 'bonus-plus-wp'), $order_id),
    149159                    );
    150160                }
  • bonus-plus-wp/trunk/inc/RestApiEndpoints.php

    r3043418 r3077704  
    1313    {
    1414        add_action('rest_api_init', [$this, 'register_endpoints'], 10);
     15        // Early enable customer WC_Session
     16        //add_action( 'init', [$this,'wc_session_enabler'] ); //https://rajaamanullah.com/how-to-use-woocommerce-sessions-and-cookies/
     17    }
     18   
     19    public static function wc_session_enabler() {
     20        if ( is_user_logged_in() || is_admin() )
     21            return;
     22   
     23        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
     24            WC()->session->set_customer_session_cookie( true );
     25        }
    1526    }
    1627
     
    131142            );
    132143           
    133             // *! Добавить Fee
     144            // *! Передаем количество бонусов
    134145            if ($args['debit'] > 0) {
    135146               
    136                 $_SESSION['bpwp_debit_bonuses'] = (int)$args['debit'];
    137                
     147                update_user_meta($user_id, 'bpwp_debit_bonuses', esc_attr($args['debit']));
     148
    138149                $response = array(
    139150                    'success' => true,
     
    145156                wp_die();
    146157            }
    147            
     158
    148159            // Код верный. Запрос проверки существования пользвателя в б+
    149160            $get_customer = bpwp_api_request(
  • bonus-plus-wp/trunk/inc/WooAccount.php

    r3043418 r3077704  
    9898        if ($info && is_array($info)) {
    9999
    100             printf('<h2>%s</h2>', 'Информация по карте лояльности');
    101             echo '<div id="loader" class="center-body"><div class="loader-ball-8"></div></div>';
    102             //do_action('bpwp_after_bonus_card_info_title');
    103             echo '<br><div id="qrcode"></div><br>';
    104 
    105100            foreach ($info as $key => $value) {
    106101                if ($key != 'person') {
    107102                    if ($key == 'discountCardName') {
    108                         printf('%s:%s<br />', esc_html(__('Тип карты', 'bonus-plus-wp')), esc_html($value));
     103                        $discountCardName = $value;
     104                        //printf('%s:%s<br />', esc_html(__('Тип карты', 'bonus-plus-wp')), esc_html($value));
    109105                    }
    110106                    if ($key == 'discountCardNumber') {
    111                         printf('%s:%s<br />', esc_html(__('Номер карты', 'bonus-plus-wp')), esc_html($value));
     107                        $discountCardNumber = $value;
     108                        //printf('%s:%s<br />', esc_html(__('Номер карты', 'bonus-plus-wp')), esc_html($value));
    112109                    }
    113110                    if ($key == 'availableBonuses') {
    114                         printf('%s:%s<br />', esc_html(__('Доступных бонусов', 'bonus-plus-wp')), esc_html($value));
     111                        $availableBonuses = $value;
     112                        //printf('%s:%s<br />', esc_html(__('Доступных бонусов', 'bonus-plus-wp')), esc_html($value));
    115113                    }
    116114                    if ($key == 'notActiveBonuses') {
    117                         printf('%s:%s<br />', esc_html(__('Неактивных бонусов', 'bonus-plus-wp')), esc_html($value));
     115                        //printf('%s:%s<br />', esc_html(__('Неактивных бонусов', 'bonus-plus-wp')), esc_html($value));
    118116                    }
    119117                    if ($key == 'purchasesTotalSum') {
    120                         printf('%s:%s<br />', esc_html(__('Сумма покупок', 'bonus-plus-wp')), esc_html($value));
     118                        $purchasesTotalSum = $value;
     119                        //printf('%s:%s<br />', esc_html(__('Сумма покупок', 'bonus-plus-wp')), esc_html($value));
    121120                    }
    122121                    if ($key == 'purchasesSumToNextCard') {
    123                         printf('%s:%s<br />', esc_html(__('Сумма покупок для смены карты', 'bonus-plus-wp')), esc_html($value));
     122                        $purchasesSumToNextCard = $value;
     123                        //printf('%s:%s<br />', esc_html(__('Сумма покупок для смены карты', 'bonus-plus-wp')), esc_html($value));
    124124                    }
    125125                    if ($key == 'lastPurchaseDate') {
    126                         printf('%s:%s<br />', esc_html(__('Последняя покупка', 'bonus-plus-wp')), esc_html($value));
     126                        //printf('%s:%s<br />', esc_html(__('Последняя покупка', 'bonus-plus-wp')), esc_html($value));
    127127                    }
    128128                } else {
     
    140140                        }
    141141                    }
    142                     }
    143142                }
    144 
     143            }
     144        include_once(BPWP_PLUGIN_DIR . 'templates/client-card.php');
    145145        } else { // нет данных в бонус+
    146146            do_action('bpwp_veryfy_client_data');
     
    191191        );
    192192        wp_enqueue_style('bpwp-bonus-loader-style');
     193        wp_enqueue_style('bpwp-user-qr-card-style');
    193194    }
    194195
  • bonus-plus-wp/trunk/inc/WooProductCatExport.php

    r3033150 r3077704  
    295295                $type = __CLASS__,
    296296                $title = __('Экспорт товаров в Бонус+, невозможен', 'bonus-plus-wp'),
    297                 $desc = __('Параметры название магазина или список продуктовпереданы неверно', 'bonus-plus-wp'),
     297                $desc = __('Параметры название магазина или список продуктов переданы неверно', 'bonus-plus-wp'),
    298298            );
    299299        }
  • bonus-plus-wp/trunk/readme.txt

    r3043418 r3077704  
    11=== WPBonusPlus ===
    2 Contributors: redmonkey73
     2Contributors: redmonkey73, mickuznetsov
    33Donate link: https://github.com/evgrezanov
    44Tags: bonus, woocommerce, sync, integration
    55Requires at least: 4.0
    6 Tested up to: 6.4.2
    7 Stable tag: 2.11
     6Tested up to: 6.5
     7Stable tag: 2.12
    88Requires PHP: 8.1
    99License: GPLv2 or later
     
    9393== Changelog ==
    9494
    95 = 2.11=
     95= 2.12 =
     96- fix bugs
     97- Вынести шаблон карты в лк в /templates
     98
     99= 2.11 =
    96100- возможность списания части бонусов на чекауте https://github.com/evgrezanov/bonus-plus-wp/issues/63
    97101- bugs fixing
Note: See TracChangeset for help on using the changeset viewer.