1
0
mirror of synced 2025-02-25 19:33:13 +03:00

ref Add API methods for loyalty program ()

rebase

rebase
This commit is contained in:
Kocmonavtik 2024-04-04 09:10:34 +03:00 committed by Uryvskiy Dima
parent 8627548d7c
commit 2cc71745c2
18 changed files with 1216 additions and 188 deletions

@ -445,6 +445,30 @@ msgstr "Se requiere clave API con acceso a una tienda"
msgid "The currency of the site differs from the currency of the store in CRM. For the integration to work correctly, the currencies in CRM and CMS must match"
msgstr "La moneda del sitio web es distinto a la tienda del CRM. Para el funcionamiento correcto de la integración, las monedas del CMS y CRM deben coincid"
msgid "Loyalty program"
msgstr "Programa de fidelización"
msgid "Activate program loyalty"
msgstr "Activar el programa de fidelización"
msgid "Enable this setting for activate program loyalty on site"
msgstr "Active esta opción para activar el programa de fidelización en el sitio web"
msgid "Terms of loyalty program"
msgstr "Condiciones del programa de fidelidad"
msgid "Insert the terms and conditions of the loyalty program"
msgstr "Inserte las condiciones de participación en el programa de fidelidad"
msgid "Conditions of personal data processing"
msgstr "Condiciones del tratamiento de datos personales"
msgid "Insert the terms and conditions for processing personal data"
msgstr "Inserte las condiciones para el tratamiento de datos personales"
msgid "To activate the loyalty program it is necessary to activate the <a href='?page=wc-settings'>'enable use of coupons option'</a>"
msgstr "Para activar el programa de fidelización es necesario activar la opción <a href='?page=wc-settings'>'habilitar uso de cupones'</a>."
msgid "Uploading services"
msgstr "Descarga de servicios"

@ -454,6 +454,111 @@ msgstr "Требуется API ключ с доступом к одному ма
msgid "The currency of the site differs from the currency of the store in CRM. For the integration to work correctly, the currencies in CRM and CMS must match"
msgstr "Валюта сайта отличается от валюты магазина в CRM. Для корректной работы интеграции, валюты в CRM и CMS должны совпадать"
msgid "Loyalty program"
msgstr "Программа лояльности"
msgid "Activate program loyalty"
msgstr "Активировать программу лояльности"
msgid "Enable this setting for activate program loyalty on site"
msgstr "Активируйте эту настройку для активации программы лояльности на сайте"
msgid "Terms of loyalty program"
msgstr "Условия программы лояльности"
msgid "Insert the terms and conditions of the loyalty program"
msgstr "Вставьте условия участия в программе лояльности"
msgid "Conditions of personal data processing"
msgstr "Условия обработки персональных данных"
msgid "Insert the terms and conditions for processing personal data"
msgstr "Вставьте условия обработки персональных данных"
msgid "To activate the loyalty program it is necessary to activate the <a href='?page=wc-settings'>'enable use of coupons option'</a>"
msgstr "Для активации программы лояльности необходимо активировать опцию <a href='?page=wc-settings'>'включить использование купонов'</a>"
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 "Error while retrieving data. Try again later"
msgstr "Ошибка при получении данных. Попробуйте позже"
msgid "Error when activating the loyalty program. Try again later"
msgstr "Ошибка при активации программы лояльности. Попробуйте позже"
msgid "Enter the correct phone number"
msgstr "Введите корректный номер телефона"
msgid "Close"
msgstr "Закрыть"
msgid "Ordinary products: accrual of 1 bonus for each %s %s"
msgstr "Обычные товары: начисление 1 бонуса за каждые %s %s"
msgid "Promotional products: accrual of 1 bonus for each %s %s"
msgstr "Акционные товары: начисление 1 бонуса за каждые %s %s"
msgid "Ordinary products: bonus accrual in the amount of %s%% of the purchase amount"
msgstr "Обычные товары: начисление бонусов в размере %s%% от суммы покупки"
msgid "Promotional products: bonus accrual in the amount of %s%% of the purchase amount"
msgstr "Акционные товары: начисление бонусов в размере %s%% от суммы покупки"
msgid "Ordinary products: %s%% discount"
msgstr "Обычные товары: %s%% скидка"
msgid "Promotional products: %s%% discount"
msgstr "Акционные товары: %s%% скидка"
msgid "Uploading services"
msgstr "Выгрузка услуг"

@ -0,0 +1,34 @@
.popup-fade-loyalty {
display: none;
}
.popup-fade-loyalty:before {
content: '';
background: #000;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0.7;
z-index: 9999;
}
.popup-loyalty {
position: fixed;
top: 20%;
left: 50%;
padding: 20px;
width: 1000px;
margin-left: -500px;
height: 50%;
background: #fff;
border: 1px solid orange;
border-radius: 4px;
z-index: 99999;
opacity: 1;
overflow: auto;
}
.popup-close-loyalty {
position: absolute;
top: 10px;
right: 10px;
}

@ -0,0 +1,121 @@
jQuery(function() {
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/)) {
if (!jQuery('#warningLoyaltyPhone').length) {
phone.parent().append('<span style="color: red" id="warningLoyaltyPhone">' + messagePhone + '</span>')
}
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('<p style="color: red">'+ response.error + '</p>')
event.preventDefault();
return false;
} else {
location.reload();
}
})
event.preventDefault();
});
jQuery('#loyaltyActivateForm').on("submit", function (event) {
var activateCheckbox = jQuery('#loyaltyActiveCheckbox');
if (activateCheckbox.length) {
if (!activateCheckbox.is(':checked')) {
event.preventDefault();
return false;
}
}
jQuery.ajax({
url: loyaltyUrl.url + '/admin-ajax.php?action=activate_customer_loyalty',
method: 'POST',
timeout: 0,
data: {ajax: 1, loyaltyId: loyaltyId},
dataType: 'json'
})
.done(function (response) {
if (response.hasOwnProperty('error')) {
jQuery('#loyaltyRegisterForm').append('<p style="color: red">'+ response.error + '</p>')
event.preventDefault();
return false;
} else {
location.reload();
}
})
event.preventDefault();
});
jQuery('.popup-open-loyalty').click(function() {
if (jQuery(this).attr('id') === 'terms-popup') {
jQuery('#popup-loyalty-text').html(termsLoyalty);
} else {
jQuery('#popup-loyalty-text').html(privacyLoyalty);
}
jQuery('.popup-fade-loyalty').fadeIn();
return false;
});
jQuery('.popup-close-loyalty').click(function() {
jQuery(this).parents('.popup-fade-loyalty').fadeOut();
return false;
});
jQuery(document).keydown(function(e) {
if (e.keyCode === 27) { // Key Escape
e.stopPropagation();
jQuery('.popup-fade-loyalty').fadeOut();
}
});
jQuery('.popup-fade-loyalty').click(function(e) {
if (jQuery(e.target).closest('.popup-loyalty').length == 0) {
jQuery(this).fadeOut();
}
});
jQuery('#phoneLoyalty').keydown(function (e) {
let key = e.key;
return (key >= '0' && key <= '9') || key == '+' || key == '(' || key == ')'|| key == '-' ||
key == 'ArrowLeft' || key == 'ArrowRight' || key == 'Delete' || key == 'Backspace';
});
});

@ -0,0 +1,36 @@
jQuery(function() {
if (jQuery('#woocommerce_integration-retailcrm_loyalty').is(':checked')) {
checkActiveCoupon();
}
jQuery('#woocommerce_integration-retailcrm_loyalty').change(function () {
if (this.checked) {
checkActiveCoupon();
}
})
function checkActiveCoupon()
{
jQuery.ajax({
url: AdminUrl.url + '/admin-ajax.php?action=get_status_coupon',
method: 'POST',
timeout: 0,
data: {ajax: 1},
dataType: 'json'
})
.done(function (response) {
if (response.coupon_status !== 'yes') {
var checkElement = jQuery('#woocommerce_integration-retailcrm_loyalty');
checkElement.parent().css('color', 'red');
checkElement.css('border-color', 'red');
checkElement.prop('checked', false);
if (!jQuery('#coupon_warning').length) {
checkElement.parent().parent().append(
"<p id='coupon_warning' style='color: red'>" + response.translate.coupon_warning + "</p>"
);
}
}
})
}
});

@ -117,6 +117,7 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
$this->form_fields['online_assistant'] = [
'title' => __('Online assistant', 'retailcrm'),
'css' => 'width:400px; height:215px; resize: horizontal;',
'type' => 'textarea',
'id' => 'online_assistant',
'placeholder' => __('Insert the Online consultant code here', 'retailcrm')
@ -593,6 +594,41 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration
'description' => __('WhatsApp chat will be opened with this contact', 'retailcrm')
];
/**
* Loyalty Program
*/
$this->form_fields[] = [
'title' => __('Loyalty program', 'retailcrm'),
'type' => 'heading',
'description' => '',
'id' => 'loyalty_options'
];
$this->form_fields['loyalty'] = [
'label' => __('Activate program loyalty', 'retailcrm'),
'title' => __('Loyalty program', 'retailcrm'),
'class' => 'checkbox',
'type' => 'checkbox',
'description' => __('Enable this setting for activate program loyalty on site', 'retailcrm')
];
$this->form_fields['loyalty_terms'] = [
'title' => __('Terms of loyalty program', 'retailcrm'),
'css' => 'width:400px; height:215px; resize: horizontal;',
'type' => 'textarea',
'id' => 'loyalty_terms',
'placeholder' => __('Insert the terms and conditions of the loyalty program', 'retailcrm')
];
$this->form_fields['loyalty_personal'] = [
'title' => __('Conditions of personal data processing', 'retailcrm'),
'css' => 'width:400px; height:215px; resize: horizontal;',
'type' => 'textarea',
'id' => 'loyalty_personal',
'placeholder' => __('Insert the terms and conditions for processing personal data', 'retailcrm')
];
/**
* Generate icml file
*/

@ -169,17 +169,7 @@ class WC_Retailcrm_Client_V5
*/
public function customersCorporateList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/customers-corporate',
@ -273,17 +263,7 @@ class WC_Retailcrm_Client_V5
*/
public function customersCorporateNotesList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/customers-corporate/notes',
@ -421,17 +401,8 @@ class WC_Retailcrm_Client_V5
) {
$this->checkIdParameter($by);
$parameters = ['by' => $by];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
$parameters['by'] = $by;
return $this->client->makeRequest(
"/customers-corporate/$id/addresses",
@ -537,17 +508,8 @@ class WC_Retailcrm_Client_V5
) {
$this->checkIdParameter($by);
$parameters = ['by' => $by];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
$parameters['by'] = $by;
return $this->client->makeRequest(
"/customers-corporate/$id/companies",
@ -640,17 +602,8 @@ class WC_Retailcrm_Client_V5
) {
$this->checkIdParameter($by);
$parameters = ['by' => $by];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
$parameters['by'] = $by;
return $this->client->makeRequest(
"/customers-corporate/$id/contacts",
@ -769,17 +722,7 @@ class WC_Retailcrm_Client_V5
*/
public function usersList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/users',
@ -840,17 +783,7 @@ class WC_Retailcrm_Client_V5
*/
public function segmentsList(array $filter = [], $limit = null, $page = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/segments',
@ -870,17 +803,7 @@ class WC_Retailcrm_Client_V5
*/
public function customFieldsList(array $filter = [], $limit = null, $page = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/custom-fields',
@ -994,17 +917,7 @@ class WC_Retailcrm_Client_V5
*/
public function customDictionariesList(array $filter = [], $limit = null, $page = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/custom-fields/dictionaries',
@ -1101,17 +1014,7 @@ class WC_Retailcrm_Client_V5
*/
public function ordersList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/orders',
@ -1445,17 +1348,7 @@ class WC_Retailcrm_Client_V5
*/
public function customersList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/customers',
@ -1666,16 +1559,8 @@ class WC_Retailcrm_Client_V5
*/
public function customersNotesList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/customers/notes',
WC_Retailcrm_Request::METHOD_GET,
@ -1748,17 +1633,7 @@ class WC_Retailcrm_Client_V5
*/
public function ordersPacksList(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/orders/packs',
@ -1899,17 +1774,7 @@ class WC_Retailcrm_Client_V5
*/
public function tasksList(array $filter = [], $limit = null, $page = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/tasks',
@ -2008,17 +1873,7 @@ class WC_Retailcrm_Client_V5
*/
public function storeProductsGroups(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/store/product-groups',
@ -2042,17 +1897,7 @@ class WC_Retailcrm_Client_V5
*/
public function storeInventories(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/store/inventories',
@ -2180,17 +2025,7 @@ class WC_Retailcrm_Client_V5
*/
public function storeProducts(array $filter = [], $page = null, $limit = null)
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
$parameters = $this->buildParameters($filter, $page, $limit);
return $this->client->makeRequest(
'/store/products',
@ -3008,6 +2843,183 @@ class WC_Retailcrm_Client_V5
);
}
/** Loyalty program */
/** Customer registration in the loyalty program */
public function createLoyaltyAccount(array $parameters, $site = null)
{
if ([] === $parameters) {
throw new InvalidArgumentException(
'Parameter `parameters` must contains a data'
);
}
return $this->client->makeRequest(
'/loyalty/account/create',
WC_Retailcrm_Request::METHOD_POST,
$this->fillSite($site, ['loyaltyAccount' => json_encode($parameters)])
);
}
/** Receiving information about participation in the loyalty program */
public function getLoyaltyClientInfo(int $clientIdLoyalty)
{
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty",
WC_Retailcrm_Request::METHOD_GET
);
}
/** Activation of participation in the loyalty program */
public function activateLoyaltyAccount(int $clientIdLoyalty)
{
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/activate",
WC_Retailcrm_Request::METHOD_POST
);
}
/** Editing participation in the loyalty program */
public function editLoyaltyAccount(int $clientIdLoyalty, array $parameters)
{
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/edit",
WC_Retailcrm_Request::METHOD_POST,
['id' => $clientIdLoyalty, 'loyaltyAccount' => json_encode($parameters)]
);
}
/** List of participation in the loyalty program */
public function getLoyaltyAccountList(array $filter = [], $limit = null, $page = null)
{
$parameters = $this->buildParameters($filter, $limit, $page);
return $this->client->makeRequest(
'/loyalty/accounts',
WC_Retailcrm_Request::METHOD_GET,
$parameters
);
}
/** List of loyalty programs */
public function getListLoyalty(array $filter = [], $limit = null, $page = null)
{
$parameters = $this->buildParameters($filter, $limit, $page);
return $this->client->makeRequest(
'/loyalty/loyalties',
WC_Retailcrm_Request::METHOD_GET,
$parameters
);
}
/** Receiving information about the loyalty program */
public function getLoyalty(int $idLoyalty)
{
return $this->client->makeRequest(
"/loyalty/loyalties/$idLoyalty",
WC_Retailcrm_Request::METHOD_GET
);
}
/** Charge bonus */
public function chargeBonusLoyalty(int $clientIdLoyalty, float $amount, string $comment = '')
{
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/bonus/charge",
WC_Retailcrm_Request::METHOD_POST,
['amount' => $amount, 'comment' => $comment]
);
}
public function creditBonusLoyalty(int $clientIdLoyalty, array $parameters)
{
if (!isset($parameters['amount'])) {
throw new InvalidArgumentException(
'Parameter `amount` does not exist'
);
}
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/bonus/credit",
WC_Retailcrm_Request::METHOD_POST,
$parameters
);
}
/** History of the client's bonus account */
public function getClientBonusHistory(int $clientIdLoyalty, array $filter = [], $limit = null, $page = null)
{
$parameters = $this->buildParameters($filter, $limit, $page);
$parameters['id'] = $clientIdLoyalty;
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/bonus/operations",
WC_Retailcrm_Request::METHOD_GET,
$parameters
);
}
public function getDetailClientBonus(
int $clientIdLoyalty,
string $status,
array $filter = [],
$limit = null,
$page = null
) {
$parameters = $this->buildParameters($filter, $limit, $page);
$parameters['id'] = $clientIdLoyalty;
$parameters['status'] = $status;
return $this->client->makeRequest(
"/loyalty/account/$clientIdLoyalty/bonus/$status/details",
WC_Retailcrm_Request::METHOD_GET,
$parameters
);
}
/** Bonus account history for all participants */
public function getBonusHistory(string $cursor, array $filter = [], $limit = null)
{
$parameters = $this->buildParameters($filter, $limit);
$parameters['cursor'] = $cursor;
return $this->client->makeRequest(
"/loyalty/bonus/operations",
WC_Retailcrm_Request::METHOD_GET,
$parameters
);
}
/** Maximum discount calculation */
public function calculateDiscountLoyalty(string $site, array $order, float $bonuses)
{
return $this->client->makeRequest(
"/loyalty/calculate",
WC_Retailcrm_Request::METHOD_POST,
['site' => $site, 'order' => json_encode($order), 'bonuses' => $bonuses]
);
}
/** Application of bonuses under the loyalty program */
public function applyBonusToOrder(string $site, array $order, float $bonuses)
{
return $this->client->makeRequest(
"/orders/loyalty/apply",
WC_Retailcrm_Request::METHOD_POST,
['site' => $site, 'order' => json_encode($order), 'bonuses' => $bonuses]
);
}
public function cancelBonusOrder(string $site, array $order)
{
return $this->client->makeRequest(
"/orders/loyalty/cancel-bonus-operations",
WC_Retailcrm_Request::METHOD_POST,
['site' => $site, 'order' => json_encode($order)]
);
}
/**
* Update CRM basic statistic
*
@ -3121,4 +3133,23 @@ class WC_Retailcrm_Client_V5
return $params;
}
protected function buildParameters(array $filter = [], $limit = null, $page = null): array
{
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (isset($page)) {
$parameters['page'] = (int) $page;
}
if (isset($limit)) {
$parameters['limit'] = (int) $limit;
}
return $parameters;
}
}

@ -33,6 +33,9 @@ if (!class_exists('WC_Retailcrm_Base')) {
/** @var WC_Retailcrm_Cart */
protected $cart;
/** @var WC_Retailcrm_Loyalty */
protected $loyalty;
/**
* Init and hook in the integration.
*
@ -86,6 +89,7 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('wp_ajax_generate_icml', [$this, 'generate_icml']);
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('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);
@ -99,6 +103,15 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('admin_enqueue_scripts', [$this, 'include_files_for_admin'], 101);
add_action('woocommerce_new_order', [$this, 'create_order'], 11, 1);
if (isset($this->settings['loyalty']) && $this->settings['loyalty'] === static::YES) {
add_action('wp_ajax_register_customer_loyalty', [$this, 'register_customer_loyalty']);
add_action('wp_ajax_activate_customer_loyalty', [$this, 'activate_customer_loyalty']);
add_action('init', [$this, 'add_loyalty_endpoint'], 11, 1);
add_action('woocommerce_account_menu_items', [$this, 'add_loyalty_item'], 11, 1);
add_action('woocommerce_account_loyalty_endpoint', [$this, 'show_loyalty'], 11, 1);
}
// Subscribed hooks
add_action('register_form', [$this, 'subscribe_register_form'], 99);
add_action('woocommerce_register_form', [$this, 'subscribe_woocommerce_register_form'], 99);
@ -127,6 +140,8 @@ if (!class_exists('WC_Retailcrm_Base')) {
add_action('woocommerce_cart_emptied', [$this, 'clear_cart']);
}
$this->loyalty = new WC_Retailcrm_Loyalty($this->apiClient, $this->settings);
// Deactivate hook
add_action('retailcrm_deactivate', [$this, 'deactivate']);
@ -607,6 +622,64 @@ if (!class_exists('WC_Retailcrm_Base')) {
$this->include_js_scripts_for_admin();
}
public function get_status_coupon()
{
echo json_encode(
[
'coupon_status' => get_option('woocommerce_enable_coupons'),
'translate' => [
'coupon_warning' => __(
"To activate the loyalty program it is necessary to activate the <a href='?page=wc-settings'>'enable use of coupons option'</a>",
'retailcrm'
)
]
]);
wp_die();
}
public function register_customer_loyalty()
{
$phone = filter_input(INPUT_POST, 'phone');
$userId = filter_input(INPUT_POST, 'userId');
$site = $this->apiClient->getSingleSiteForKey();
$isSuccessful = false;
if (!empty($site) && $userId && $phone) {
$isSuccessful = $this->loyalty->registerCustomer($userId, $phone, $site);
}
if (!$isSuccessful) {
writeBaseLogs('Errors when registering a loyalty program. Passed parameters: ' .
json_encode(['site' => $site, 'userId' => $userId, 'phone' => $phone])
);
echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later', 'retailcrm')]);
} else {
echo json_encode(['isSuccessful' => true]);
}
wp_die();
}
public function activate_customer_loyalty()
{
$loyaltyId = filter_input(INPUT_POST, 'loyaltyId');
$isSuccessful = false;
if ($loyaltyId) {
$isSuccessful = $this->loyalty->activateLoyaltyCustomer($loyaltyId);
}
if (!$isSuccessful) {
writeBaseLogs('Errors when activate loyalty program. Passed parameters: ' . json_encode(['loyaltyId' => $loyaltyId]));
echo json_encode(['error' => __('Error when activating the loyalty program. Try again later', 'retailcrm')]);
} else {
echo json_encode(['isSuccessful' => true]);
}
wp_die();
}
/**
* In this method we include CSS file
*
@ -645,9 +718,10 @@ if (!class_exists('WC_Retailcrm_Base')) {
'retailcrm-cron-info',
'retailcrm-meta-fields',
'retailcrm-module-settings',
'retailcrm-loyalty'
];
$wpAdminUrl = ['url' => get_admin_url()];
$wpAdminUrl = ['url' => get_admin_url()];
$jsScriptsPath = plugins_url() . '/woo-retailcrm/assets/js/';
foreach ($jsScripts as $scriptName) {
@ -803,6 +877,53 @@ if (!class_exists('WC_Retailcrm_Base')) {
wp_die();
}
public function add_loyalty_item($items)
{
$items['loyalty'] = __('Loyalty program', 'retailcrm');
return $items;
}
public function add_loyalty_endpoint()
{
add_rewrite_endpoint('loyalty', EP_PAGES);
}
public function show_loyalty()
{
$userId = get_current_user_id();
if (!isset($userId)) {
return;
}
$jsScript = 'retailcrm-loyalty-actions';
$loyaltyUrl = ['url' => get_admin_url()];
$jsScriptsPath = plugins_url() . '/woo-retailcrm/assets/js/';
$cssPath = plugins_url() . '/woo-retailcrm/assets/css/';
$messagePhone = __('Enter the correct phone number', 'retailcrm');
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);
wp_localize_script($jsScript, 'messagePhone', $messagePhone);
wp_localize_script($jsScript, 'termsLoyalty', $this->settings['loyalty_terms']);
wp_localize_script($jsScript, 'privacyLoyalty', $this->settings['loyalty_personal']);
wp_register_style('retailcrm-loyalty-style', $cssPath . 'retailcrm-loyalty-style.css', false, '0.1');
wp_enqueue_style('retailcrm-loyalty-style');
$result = $this->loyalty->getForm($userId);
if ([] === $result) {
echo '<p style="color: red">'. __('Error while retrieving data. Try again later', 'retailcrm') . '</p>';
} else {
wp_localize_script($jsScript, 'loyaltyId', $result['loyaltyId'] ?? null);
echo $result['form'];
}
}
/**
* Get custom fields with CRM
*

@ -0,0 +1,121 @@
<?php
if (!class_exists('WC_Retailcrm_Loyalty')) :
if (!class_exists('WC_Retailcrm_Loyalty_Form')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('include/components/class-wc-retailcrm-loyalty-form.php'));
}
/**
* PHP version 7.0
*
* Class WC_Retailcrm_Loyalty - Allows transfer data carts with CMS.
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Loyalty
{
/** @var WC_Retailcrm_Client_V5 */
protected $apiClient;
protected $dateFormat;
protected $settings;
/** @var WC_Retailcrm_Loyalty_Form */
protected $loyaltyForm;
public function __construct($apiClient, $settings)
{
$this->apiClient = $apiClient;
$this->settings = $settings;
$this->dateFormat = 'Y-m-d H:i:sP';
$this->loyaltyForm = new WC_Retailcrm_Loyalty_Form();
}
public function getForm(int $userId)
{
$result = [];
try {
$response = $this->apiClient->customersGet($userId);
if (!isset($response['customer']['id'])) {
return $result;
}
$filter['customerId'] = $response['customer']['id'];
$response = $this->apiClient->getLoyaltyAccountList($filter);
} catch (Throwable $exception) {
writeBaseLogs('Exception get loyalty accounts: ' . $exception->getMessage());
return $result;
}
if (!$response->isSuccessful() || !$response->offsetExists('loyaltyAccounts')) {
return $result;
}
$loyaltyAccount = $response['loyaltyAccounts'][0] ?? null;
if ($loyaltyAccount && (int) $loyaltyAccount['customer']['externalId'] === $userId) {
if ($loyaltyAccount['active'] === true) {
$result['form'] = $this->loyaltyForm->getInfoLoyalty($loyaltyAccount);
} else {
$result['form'] = $this->loyaltyForm->getActivationForm();
$result['loyaltyId'] = $loyaltyAccount['id'];
}
} else {
$result['form'] = $this->loyaltyForm->getRegistrationForm();
}
return $result;
}
public function registerCustomer(int $userId, string $phone, string $site): bool
{
$parameters = [
'phoneNumber' => $phone,
'customer' => [
'externalId' => $userId
]
];
try {
$response = $this->apiClient->createLoyaltyAccount($parameters, $site);
if (!$response->isSuccessful()) {
writeBaseLogs('Error while registering in the loyalty program: ' . $response->getRawResponse());
}
return $response->isSuccessful();
} catch (Throwable $exception) {
writeBaseLogs('Exception while registering in the loyalty program: ' . $exception->getMessage());
return false;
}
}
public function activateLoyaltyCustomer(int $loyaltyId)
{
try {
$response = $this->apiClient->activateLoyaltyAccount($loyaltyId);
if (!$response->isSuccessful()) {
writeBaseLogs('Error while registering in the loyalty program: ' . $response->getRawResponse());
}
return $response->isSuccessful();
} catch (Throwable $exception) {
writeBaseLogs('Exception while activate loyalty account: ' . $exception->getMessage());
return false;
}
}
}
endif;

@ -0,0 +1,90 @@
<?php
if (!class_exists('WC_Retailcrm_Loyalty')) :
class WC_Retailcrm_Loyalty_Form
{
public function getRegistrationForm()
{
return sprintf(
'
<form id="loyaltyRegisterForm" method="post">
<p>%s</p>
<p><input type="checkbox" name="terms" id="termsLoyalty" required>%s<a id="terms-popup" class="popup-open-loyalty" href="#">%s</a>.</p>
<p><input type="checkbox" name="privacy" id="privacyLoyalty" required>%s<a id="privacy-popup" class="popup-open-loyalty" href="#">%s</a>.</p>
<p><input type="text" name="phone" id="phoneLoyalty" placeholder="%s" required></p>
<p><input type="submit" value="%s"></p>
</form>
<div class="popup-fade-loyalty">
<div class="popup-loyalty">
<a class="popup-close-loyalty" href="#">%s</a>
<br>
<div id="popup-loyalty-text"></div>
</div>
</div>
',
__('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'),
__('Close', 'retailcrm')
);
}
public function getActivationForm()
{
return sprintf('
<form id="loyaltyActivateForm" method="post">
<p><input type="checkbox" id="loyaltyActiveCheckbox" name="loyaltyCheckbox" required> %s</p>
<input type="submit" value="%s">
</form>',
__('Activate participation in the loyalty program', 'retailcrm'),
__('Send', 'retailcrm')
);
}
public function getInfoLoyalty(array $loyaltyAccount)
{
$data = [
'<b>' . __('Bonus account', 'retailcrm') . '</b>',
__('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'],
'<br>',
'<b>' . __('Current level rules', 'retailcrm') . '</b>',
__('Required amount of purchases to move to the next level: ', 'retailcrm') . $loyaltyAccount['nextLevelSum'] . ' ' . $loyaltyAccount['loyalty']['currency']
];
switch ($loyaltyAccount['level']['type']) {
case 'bonus_converting':
$data[] = sprintf(__('Ordinary products: accrual of 1 bonus for each %s %s', 'retailcrm'), $loyaltyAccount['level']['privilegeSize'], $loyaltyAccount['loyalty']['currency']);
$data[] = sprintf(__('Promotional products: accrual of 1 bonus for each %s %s', 'retailcrm'), $loyaltyAccount['level']['privilegeSizePromo'], $loyaltyAccount['loyalty']['currency']);
break;
case 'bonus_percent':
$data[] = sprintf(__('Ordinary products: bonus accrual in the amount of %s%% of the purchase amount', 'retailcrm'), $loyaltyAccount['level']['privilegeSize']);
$data[] = sprintf(__('Promotional products: bonus accrual in the amount of %s%% of the purchase amount', 'retailcrm'), $loyaltyAccount['level']['privilegeSizePromo']);
break;
case 'discount':
$data[] = sprintf(__('Ordinary products: %s%% discount', 'retailcrm'), $loyaltyAccount['level']['privilegeSize']);
$data[] = sprintf(__('Promotional products: %s%% discount', 'retailcrm'), $loyaltyAccount['level']['privilegeSizePromo']);
break;
}
$result = '';
foreach ($data as $line) {
$result .= "<p style='line-height: 1'>$line</p>";
}
return $result;
}
}
endif;

Binary file not shown.

Binary file not shown.

@ -121,6 +121,7 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
require_once(self::checkCustomFile('include/icml/class-wc-retailcrm-icml-writer.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-orders.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-cart.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-loyalty.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-customers.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-inventories.php'));
require_once(self::checkCustomFile('include/class-wc-retailcrm-history.php'));
@ -132,6 +133,7 @@ if (!class_exists( 'WC_Integration_Retailcrm')) :
require_once(self::checkCustomFile('include/validators/url-validator/class-wc-retailcrm-url-constraint.php'));
require_once(self::checkCustomFile('include/validators/url-validator/class-wc-retailcrm-url-validator.php'));
require_once(self::checkCustomFile('include/validators/class-wc-retailcrm-validator-exception.php'));
require_once(self::checkCustomFile('include/components/class-wc-retailcrm-loyalty-form.php'));
}
/**

@ -0,0 +1,76 @@
<?php
namespace datasets;
/**
* PHP version 7.0
*
* Class DataLoyaltyRetailCrm - Data set for WC_Retailcrm_Loyalty_Test.
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class DataLoyaltyRetailCrm
{
public static function getDataLoyalty()
{
return [
[
'isSuccessful' => true,
'body' => json_encode(['loyaltyAccounts' => []]),
'expected' => 'id="loyaltyRegisterForm"'
],
[
'isSuccessful' => true,
'body' => json_encode(
[
'loyaltyAccounts' => [
0 => [
'active' => false,
'customer' => [
'externalId' => 1
],
'id' => 1
]
]
]
),
'expected' => 'id="loyaltyActivateForm"'
],
[
'isSuccessful' => true,
'body' => json_encode(
[
'loyaltyAccounts' => [
0 => [
'id' => 1,
'level' => [
'name' => 'Test level',
'privilegeSize' => 5,
'privilegeSizePromo' => 3,
'type' => 'bonus_converting'
],
'amount' => 1000,
'cardNumber' => '12345',
'activatedAt' => '2024-04-10 15:00:00',
'nextLevelSum' => 15000,
'loyalty' => [
'currency' => 'USD'
],
'customer' => [
'externalId' => 1
],
'active' => true
]
]
]
),
'expected' => 'Ordinary products: accrual of 1 bonus for each'
],
];
}
}

@ -80,7 +80,10 @@ class WC_Retailcrm_Test_Case_Helper extends WC_Unit_Test_Case
'product_description' => 'full',
'stores_for_uploading' => ['woocommerce', 'main'],
'woo_coupon_apply_field' => 'testField',
'icml_unload_services' => 'yes'
'icml_unload_services' => 'yes',
'loyalty' => 'yes',
'loyalty_terms' => 'Test terms',
'loyalty_personal' => 'Test privacy'
];
update_option(WC_Retailcrm_Base::$option_key, $options);

@ -0,0 +1,131 @@
<?php
if (!class_exists('WC_Retailcrm_Client_V5')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('include/api/class-wc-retailcrm-client-v5.php'));
}
/**
* PHP version 7.0
*
* Class WC_Retailcrm_Loyalty_Client_Test
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Loyalty_Client_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $responseMock;
protected $apiMock;
/** @var \WC_Retailcrm_Client_V5 */
protected $clientMock;
public function setUp()
{
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(['isSuccessful'])
->getMock()
;
$this->responseMock->setResponse(['success' => true]);
$this->setMockResponse($this->responseMock, 'isSuccessful', true);
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Request')
->disableOriginalConstructor()
->setMethods(['makeRequest'])
->getMock()
;
$this->setMockResponse($this->apiMock, 'makeRequest', $this->responseMock);
$this->clientMock = new \WC_Retailcrm_Client_V5('https://test@retailcrm.ru', 'test', 'test');
$reflection = new ReflectionClass($this->clientMock);
$reflection_property = $reflection->getProperty('client');
$reflection_property->setAccessible(true);
$reflection_property->setValue($this->clientMock, $this->apiMock);
}
/**
* @dataProvider requestLoyaltyData
*/
public function testLoyaltyRequest($method, $parameters)
{
/** @var WC_Retailcrm_Response $test */
$test = call_user_func([$this->clientMock, $method], ...$parameters);
$this->assertTrue($test->isSuccessful());
}
public function requestLoyaltyData()
{
return [
[
'method' => 'createLoyaltyAccount',
'parameters' => [['test'], 'testSite']
],
[
'method' => 'getLoyaltyClientInfo',
'parameters' => [1]
],
[
'method' => 'activateLoyaltyAccount',
'parameters' => [1]
],
[
'method' => 'editLoyaltyAccount',
'parameters' => [1, ['test']]
],
[
'method' => 'getLoyaltyAccountList',
'parameters' => [['filter'], 20, 1]
],
[
'method' => 'getListLoyalty',
'parameters' => [['filter'], 20, 1]
],
[
'method' => 'getLoyalty',
'parameters' => [1]
],
[
'method' => 'chargeBonusLoyalty',
'parameters' => [1, 100, 'test']
],
[
'method' => 'creditBonusLoyalty',
'parameters' => [1, ['amount' => 100]]
],
[
'method' => 'getClientBonusHistory',
'parameters' => [1, ['filter'], 20, 1]
],
[
'method' => 'getDetailClientBonus',
'parameters' => [1, 'status', ['filter'], 20, 1]
],
[
'method' => 'getBonusHistory',
'parameters' => ['cursor', ['filter'], 20]
],
[
'method' => 'calculateDiscountLoyalty',
'parameters' => ['site', ['order'], 100]
],
[
'method' => 'applyBonusToOrder',
'parameters' => ['site', ['order'], 100]
],
[
'method' => 'cancelBonusOrder',
'parameters' => ['site', ['order']]
],
];
}
}

@ -132,6 +132,11 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper
$this->assertArrayHasKey('bind_by_sku', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('update_number', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('product_description', $this->baseRetailcrm->form_fields);
//loyalty
$this->assertArrayHasKey('loyalty', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('loyalty_terms', $this->baseRetailcrm->form_fields);
$this->assertArrayHasKey('loyalty_personal', $this->baseRetailcrm->form_fields);
}
public function test_retailcrm_form_fields_value()

@ -0,0 +1,92 @@
<?php
use datasets\DataLoyaltyRetailCrm;
if (!class_exists('WC_Retailcrm_Loyalty')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('class-wc-retailcrm-loyalty.php'));
}
if (!class_exists('WC_Retailcrm_Response')) {
include_once(WC_Integration_Retailcrm::checkCustomFile('include/api/class-wc-retailcrm-response.php'));
}
/**
* PHP version 7.0
*
* Class WC_Retailcrm_Loyalty_Test
*
* @category Integration
* @author RetailCRM <integration@retailcrm.ru>
* @license http://retailcrm.ru Proprietary
* @link http://retailcrm.ru
* @see http://help.retailcrm.ru
*/
class WC_Retailcrm_Loyalty_Test extends WC_Retailcrm_Test_Case_Helper
{
protected $responseMock;
protected $apiMock;
/** @var \WC_Retailcrm_Loyalty */
protected $loyalty;
public function setUp()
{
$this->responseMock = $this->getMockBuilder('\WC_Retailcrm_Response_Helper')
->disableOriginalConstructor()
->setMethods(['isSuccessful'])
->getMock()
;
$this->responseMock->setResponse(['success' => true]);
$this->setMockResponse($this->responseMock, 'isSuccessful', true);
$this->apiMock = $this->getMockBuilder('\WC_Retailcrm_Client_V5')
->disableOriginalConstructor()
->setMethods(['customersGet', 'getLoyaltyAccountList', 'createLoyaltyAccount', 'activateLoyaltyAccount'])
->getMock()
;
$this->setMockResponse($this->apiMock, 'customersGet', ['customer' => ['id' => 1]]);
$this->setMockResponse($this->apiMock, 'createLoyaltyAccount', $this->responseMock);
$this->setMockResponse($this->apiMock, 'activateLoyaltyAccount', $this->responseMock);
$this->loyalty = new WC_Retailcrm_Loyalty($this->apiMock, []);
}
/**
* @dataProvider responseLoyalty
*/
public function testGetForm($isSuccessful, $body, $expected)
{
$response = new WC_Retailcrm_Response($isSuccessful ? 200 : 400, $body);
$this->setMockResponse($this->apiMock, 'getLoyaltyAccountList', $response);
$this->loyalty = new WC_Retailcrm_Loyalty($this->apiMock, []);
$result = $this->loyalty->getForm(1);
if (isset($result['form'])) {
$this->assertTrue((bool) stripos($result['form'], $expected));
}
}
public function testRegistrationLoyalty()
{
$result = $this->loyalty->registerCustomer(1, '89999999999', 'test');
$this->assertTrue($result);
}
public function testActivateLoyalty()
{
$result = $this->loyalty->activateLoyaltyCustomer(1);
$this->assertTrue($result);
}
public function responseLoyalty()
{
return DataLoyaltyRetailCrm::getDataLoyalty();
}
}