diff --git a/resources/pot/retailcrm-ru_RU.pot b/resources/pot/retailcrm-ru_RU.pot index c148d14..7d974d4 100644 --- a/resources/pot/retailcrm-ru_RU.pot +++ b/resources/pot/retailcrm-ru_RU.pot @@ -477,3 +477,69 @@ msgstr "Вставьте условия обработки персональн msgid "To activate the loyalty program it is necessary to activate the 'enable use of coupons option'" msgstr "Для активации программы лояльности необходимо активировать опцию 'включить использование купонов'" + +msgid "Bonus account" +msgstr "Бонусный счёт" + +msgid "Participation ID" +msgstr "ID участия" + +msgid "Current level" +msgstr "Текущий уровень" + +msgid "Bonuses on the account" +msgstr "Бонусов на счёте" + +msgid "Bonus card number" +msgstr "Номер бонусной карты" + +msgid "Date of registration" +msgstr "Дата регистрации" + +msgid "Current level rules" +msgstr "Правила текущего уровня" + +msgid "Required amount of purchases to move to the next level" +msgstr "Необходимая сумма покупок для перехода на следующий уровень" + +msgid "Activate participation in the loyalty program" +msgstr "Активировать участие в программе лояльности" + +msgid "Send" +msgstr "Отправить" + +msgid "To register in the Loyalty Program, fill in the form:" +msgstr "Для регистрации в Программе лояльности заполните форму:" + +msgid " I agree with " +msgstr " Я согласен с " + +msgid "loyalty program terms" +msgstr "условиями программы лояльности" + +msgid "terms of personal data processing" +msgstr "условиями обработки персональных данных" + +msgid "Phone" +msgstr "Телефон" + +msgid "Error while registering in the loyalty program. Try again later." +msgstr "Ошибка при регистрации в программе лояльности. Попробуйте позже." + +msgid "The card is not linked" +msgstr "Карта не привязана" + +msgid "Ordinary goods" +msgstr "Обычные товары" + +msgid "Promotional products" +msgstr "Акционные товары" + +msgid "bonus for every" +msgstr "бонус за каждые" + +msgid "bonuses" +msgstr "бонусов" + +msgid "discount" +msgstr "скидка" diff --git a/src/assets/js/retailcrm-loyalty-actions.js b/src/assets/js/retailcrm-loyalty-actions.js index 5351fae..85ec0fb 100644 --- a/src/assets/js/retailcrm-loyalty-actions.js +++ b/src/assets/js/retailcrm-loyalty-actions.js @@ -1,3 +1,50 @@ jQuery(function() { - alert('HOBA'); + jQuery('#loyaltyRegisterForm').on("submit", function (event) { + var termsCheck = jQuery('#termsLoyalty'); + var privacyCheck = jQuery('#privacyLoyalty'); + + if (termsCheck.length) { + if (!termsCheck.is(':checked')) { + event.preventDefault(); + return false; + } + } + + if (privacyCheck.length) { + if (!privacyCheck.is(':checked')) { + event.preventDefault(); + return false; + } + } + + let phone = jQuery('#phoneLoyalty'); + + if (!phone.val().match(/(?:\+|\d)[\d\-\(\) ]{7,}\d/)) { + phone.parent().append('test') + + event.preventDefault(); + return false; + } else { + jQuery('#warningLoyaltyPhone').remove(); + } + + jQuery.ajax({ + url: LoyaltyUrl.url + '/admin-ajax.php?action=register_customer_loyalty', + method: 'POST', + timeout: 0, + data: {ajax: 1, phone: phone.val(), userId: customerId}, + dataType: 'json' + }) + .done(function (response) { + if (response.hasOwnProperty('error')) { + jQuery('#loyaltyRegisterForm').append('
'+ response.error + '
') + + event.preventDefault(); + return false; + } else { + alert('success'); + return true; + } + }) + }); }); diff --git a/src/include/class-wc-retailcrm-base.php b/src/include/class-wc-retailcrm-base.php index 247bedb..a605984 100644 --- a/src/include/class-wc-retailcrm-base.php +++ b/src/include/class-wc-retailcrm-base.php @@ -90,6 +90,7 @@ if (!class_exists('WC_Retailcrm_Base')) { add_action('wp_ajax_upload_selected_orders', [$this, 'upload_selected_orders']); add_action('wp_ajax_clear_cron_tasks', [$this, 'clear_cron_tasks']); add_action('wp_ajax_get_status_coupon', [$this, 'get_status_coupon']); + add_action('wp_ajax_register_customer_loyalty', [$this, 'register_customer_loyalty']); add_action('admin_print_footer_scripts', [$this, 'ajax_generate_icml'], 99); add_action('woocommerce_update_customer', [$this, 'update_customer'], 10, 1); add_action('user_register', [$this, 'create_customer'], 10, 2); @@ -629,6 +630,33 @@ if (!class_exists('WC_Retailcrm_Base')) { wp_die(); } + public function register_customer_loyalty() + { + $phone = filter_input(INPUT_POST, 'phone'); + $userId = filter_input(INPUT_POST, 'userId'); + + $site = $this->apiClient->getSingleSiteForKey(); + + if (empty($site)) { + writeBaseLogs('Error with CRM credentials: need an valid apiKey assigned to one certain site'); + echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later.', 'retailcrm')]); + } + + if (!$userId || !$phone) { + writeBaseLogs('Errors when registering a loyalty program. Passed parameters: userId = ' . $userId ?? 'NULL' . ' phone = ' . $phone ?? 'NULL'); + echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later.', 'retailcrm')]); + } + + $response = $this->loyalty->registerCustomer($userId, $phone, $site); + + if (!$response->isSuccessful()) { + writeBaseLogs('Error while registering in the loyalty program: ' . $response->getRawResponse()); + echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later.', 'retailcrm')]); + } + + wp_die(); + } + /** * In this method we include CSS file * @@ -827,7 +855,7 @@ if (!class_exists('WC_Retailcrm_Base')) { public function add_loyalty_item($items) { - $items['loyalty'] = __('Loyalty program'); + $items['loyalty'] = __('Loyalty program', 'retailcrm'); return $items; } @@ -839,8 +867,6 @@ if (!class_exists('WC_Retailcrm_Base')) { public function show_loyalty() { - global $wp; - $userId = get_current_user_id(); if (!isset($userId)) { @@ -848,12 +874,13 @@ if (!class_exists('WC_Retailcrm_Base')) { } $jsScript = 'retailcrm-loyalty-actions'; - $loyaltyUrl = home_url(add_query_arg([], $wp->request)); + $loyaltyUrl = ['url' => get_admin_url()]; $jsScriptsPath = plugins_url() . '/woo-retailcrm/assets/js/'; wp_register_script($jsScript, $jsScriptsPath . $jsScript . '.js', false, '0.1'); wp_enqueue_script($jsScript, $jsScriptsPath . $jsScript . '.js', '', '', true); wp_localize_script($jsScript, 'LoyaltyUrl', $loyaltyUrl); + wp_localize_script($jsScript, 'customerId', $userId); echo $this->loyalty->getForm($userId); } diff --git a/src/include/class-wc-retailcrm-loyalty.php b/src/include/class-wc-retailcrm-loyalty.php index c13339c..77e7e2c 100644 --- a/src/include/class-wc-retailcrm-loyalty.php +++ b/src/include/class-wc-retailcrm-loyalty.php @@ -48,37 +48,92 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : if (isset($response['loyaltyAccounts'][0]) && (int)$loyaltyAccount['customer']['externalId'] === $userId) { if ($loyaltyAccount['active'] === true) { - $result = ' -Бонусный счёт
-ID участия: TEST
-Статус участия: ТЕСТ
-Текущий уровень: ТЕСТ
-И так далее
- '; + $result = $this->getLoyaltyInfo($loyaltyAccount); } else { - $result = ' - - '; + $result = sprintf( + ' + ', + __('Activate participation in the loyalty program', 'retailcrm'), + __('Send', 'retailcrm') + ); } } else { - $result = ' - - '; + $result = sprintf( + ' + ', + __('To register in the Loyalty Program, fill in the form:', 'retailcrm'), + __(' I agree with ', 'retailcrm'), + __('loyalty program terms', 'retailcrm'), + __(' I agree with ', 'retailcrm'), + __('terms of personal data processing', 'retailcrm'), + __('Phone', 'retailcrm'), + __('Send', 'retailcrm') + ); } return $result; } + + public function registerCustomer(int $userId, string $phone, string $site): WC_Retailcrm_Response + { + $parameters = [ + 'phoneNumber' => $phone, + 'customer' => [ + 'externalId' => $userId + ] + ]; + + return $this->apiClient->createLoyaltyAccount($parameters, $site); + } + + private function getLoyaltyInfo(array $loyaltyAccount) + { + $data = [ + '' . __('Bonus account', 'retailcrm') . '', + __('Participation ID', 'retailcrm') . ': ' . $loyaltyAccount['id'], + __('Current level', 'retailcrm') . ': ' . $loyaltyAccount['level']['name'], + __('Bonuses on the account', 'retailcrm') . ': ' . $loyaltyAccount['amount'], + __('Bonus card number' , 'retailcrm') . ': ' . ($loyaltyAccount['cardNumber'] ?? __('The card is not linked', 'retailcrm')), + __('Date of registration', 'retailcrm') . ': ' . $loyaltyAccount['activatedAt'], + '$line
"; + } + + return $result; + } } endif; diff --git a/src/languages/retailcrm-ru_RU.mo b/src/languages/retailcrm-ru_RU.mo index 6aaec63..1604a87 100644 Binary files a/src/languages/retailcrm-ru_RU.mo and b/src/languages/retailcrm-ru_RU.mo differ