diff --git a/CHANGELOG.md b/CHANGELOG.md index 6714a138..451dbd6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2024-06-05 v.6.5.18 +- Добавлена возможность исправления даты регистрации клиентов в CRM + ## 2024-06-04 v.6.5.17 - Добавлена передача признака маркировки товара в ICML каталоге diff --git a/intaro.retailcrm/classes/general/user/RetailCrmUser.php b/intaro.retailcrm/classes/general/user/RetailCrmUser.php index eebdf7bd..dc454941 100644 --- a/intaro.retailcrm/classes/general/user/RetailCrmUser.php +++ b/intaro.retailcrm/classes/general/user/RetailCrmUser.php @@ -11,6 +11,8 @@ IncludeModuleLangFile(__FILE__); +use Bitrix\Main\UserTable; + /** * Class RetailCrmUser * @@ -198,4 +200,68 @@ class RetailCrmUser return $result; } + + public static function fixDateCustomer(): void + { + CAgent::RemoveAgent("RetailCrmUser::fixDateCustomer();", RetailcrmConstants::MODULE_ID); + COption::SetOptionString(RetailcrmConstants::MODULE_ID, RetailcrmConstants::OPTION_FIX_DATE_CUSTOMER, 'Y'); + + $startId = COption::GetOptionInt(RetailcrmConstants::MODULE_ID, RetailcrmConstants::OPTION_FIX_DATE_CUSTOMER_LAST_ID, 0); + $api = new RetailCrm\ApiClient(RetailcrmConfigProvider::getApiUrl(), RetailcrmConfigProvider::getApiKey()); + $optionsSitesList = RetailcrmConfigProvider::getSitesList(); + $limit = 50; + $offset = 0; + + while(true) { + try { + $usersResult = UserTable::getList([ + 'select' => ['ID', 'DATE_REGISTER', 'LID'], + 'filter' => ['>ID' => $startId], + 'order' => ['ID'], + 'limit' => $limit, + 'offset' => $offset, + ]); + } catch (\Throwable $exception) { + Logger::getInstance()->write($exception->getMessage(), 'fixDateCustomers'); + + break; + } + + $users = $usersResult->fetchAll(); + + if ($users === []) { + break; + } + + foreach ($users as $user) { + $site = null; + + if ($optionsSitesList) { + if (isset($user['LID']) && array_key_exists($user['LID'], $optionsSitesList) && $optionsSitesList[$user['LID']] !== null) { + $site = $optionsSitesList[$user['LID']]; + } else { + continue; + } + } + + $customer['externalId'] = $user['ID']; + + try { + $date = new \DateTime($user['DATE_REGISTER']); + $customer['createdAt'] = $date->format('Y-m-d H:i:s'); + + RCrmActions::apiMethod($api, 'customersEdit', __METHOD__, $customer, $site); + } catch (\Throwable $exception) { + Logger::getInstance()->write($exception->getMessage(), 'fixDateCustomers'); + continue; + } + + time_nanosleep(0, 250000000); + } + + COption::SetOptionInt(RetailcrmConstants::MODULE_ID, RetailcrmConstants::OPTION_FIX_DATE_CUSTOMER_LAST_ID, end($users)['ID']); + + $offset += $limit; + } + } } diff --git a/intaro.retailcrm/description.ru b/intaro.retailcrm/description.ru index 03326223..85149670 100644 --- a/intaro.retailcrm/description.ru +++ b/intaro.retailcrm/description.ru @@ -1 +1 @@ -- Добавлена передача признака маркировки товара в ICML каталоге +- Добавлена возможность исправления даты регистрации клиентов в CRM diff --git a/intaro.retailcrm/install/version.php b/intaro.retailcrm/install/version.php index 860b00ff..6251607c 100644 --- a/intaro.retailcrm/install/version.php +++ b/intaro.retailcrm/install/version.php @@ -1,6 +1,6 @@ '6.5.17', - 'VERSION_DATE' => '2024-06-04 12:00:00' + 'VERSION' => '6.5.18', + 'VERSION_DATE' => '2024-06-05 16:30:00' ]; diff --git a/intaro.retailcrm/lang/en/options.php b/intaro.retailcrm/lang/en/options.php index 9ac239eb..5e6da8ea 100644 --- a/intaro.retailcrm/lang/en/options.php +++ b/intaro.retailcrm/lang/en/options.php @@ -148,3 +148,9 @@ $MESS ['ERROR_LINK_INTEGRATION_PAYMENT'] = 'Error in comparing integration payme $MESS ['ERROR_UPDATE_PAYMENT_TYPES_DELIVERY'] = 'Error when updating payment methods for deliveries'; $MESS ['INTEGRATION_PAYMENT_LABEL'] = 'When correlating CMS and CRM integration payments, a regular payment is created on the system side to which orders will be linked.'; $MESS ['NEED_PERMISSIONS_REFERENCE_LABEL'] = 'For this option to work correctly, the api key needs access to receive and edit reference book'; + +$MESS ['FIX_UPLOAD_CUSTOMER_HEADER'] = 'Fix customer registration date in CRM'; +$MESS ['FIX_UPLOAD_CUSTOMER_BUTTON_LABEL'] = 'Correct customer registration date in CRM'; +$MESS ['FIX_UPLOAD_CUSTOMER_INFO'] = 'When you press this button, an agent will be created to launch the script. Please note that the script execution time may vary depending on the number of clients in the database. To minimize possible disruptions to the script operation, it is recommended to launch it at night time. This script can only be launched once'; +$MESS ['FIX_UPLOAD_CUSTOMER_AFTER_SUBMIT'] = 'The agent has been created and will be launched soon'; +$MESS ['FIX_UPLOAD_CUSTOMER_AFTER_SUBMIT_ERROR'] = 'An error occurred while adding an agent'; diff --git a/intaro.retailcrm/lang/ru/options.php b/intaro.retailcrm/lang/ru/options.php index 0605b7fe..d57691e9 100644 --- a/intaro.retailcrm/lang/ru/options.php +++ b/intaro.retailcrm/lang/ru/options.php @@ -207,3 +207,9 @@ $MESS ['ERROR_LINK_INTEGRATION_PAYMENT'] = 'Ошибка при сопостав $MESS ['ERROR_UPDATE_PAYMENT_TYPES_DELIVERY'] = 'Ошибка при обновлении способов оплаты для доставок'; $MESS ['INTEGRATION_PAYMENT_LABEL'] = 'При сопоставлении интеграционных оплат CRM, на стороне системы создаётся обычная оплата, к которой будут привязываться заказы.'; $MESS ['NEED_PERMISSIONS_REFERENCE_LABEL'] = 'Для корректной работы опции апи-ключу необходимы доступы на получение и редактирование справочников'; + +$MESS ['FIX_UPLOAD_CUSTOMER_HEADER'] = 'Исправление даты регистрации клиентов в CRM'; +$MESS ['FIX_UPLOAD_CUSTOMER_BUTTON_LABEL'] = 'Исправить дату регистрации клиентов в CRM'; +$MESS ['FIX_UPLOAD_CUSTOMER_INFO'] = 'При нажатии на эту кнопку будет создан агент для запуска скрипта. Обратите внимание, что время выполнения скрипта может варьироваться в зависимости от количества клиентов в базе данных. Для минимизации возможных нарушений в работе скрипта рекомендуется запускать его в ночное время. Этот скрипт может быть запущен только один раз.'; +$MESS ['FIX_UPLOAD_CUSTOMER_AFTER_SUBMIT'] = 'Агент создан и запустится в ближайшее время'; +$MESS ['FIX_UPLOAD_CUSTOMER_AFTER_SUBMIT_ERROR'] = 'Возникла ошибка при добавлении агента'; diff --git a/intaro.retailcrm/lib/component/constants.php b/intaro.retailcrm/lib/component/constants.php index 5a704b54..f18e2a21 100644 --- a/intaro.retailcrm/lib/component/constants.php +++ b/intaro.retailcrm/lib/component/constants.php @@ -125,4 +125,7 @@ class Constants 'custom_fields_read' => 'custom_fields_read', 'custom_fields_write' => 'custom_fields_write' ]; + + public const OPTION_FIX_DATE_CUSTOMER = 'once_upload_customer'; + public const OPTION_FIX_DATE_CUSTOMER_LAST_ID = 'last_id_customer_fix'; } diff --git a/intaro.retailcrm/options.php b/intaro.retailcrm/options.php index 8bd8d3c2..442c0d22 100644 --- a/intaro.retailcrm/options.php +++ b/intaro.retailcrm/options.php @@ -232,6 +232,27 @@ if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_RE die(json_encode($res)); } +if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') && isset($_POST['ajax']) && $_POST['ajax'] == 3) { + $dateAgent = new DateTime(); + $intAgent = new DateInterval('PT60S'); + $dateAgent->add($intAgent); + + CAgent::AddAgent( + "RetailCrmUser::fixDateCustomer();", + $mid, + "N", + 9999999, + $dateAgent->format('d.m.Y H:i:s'), + "Y", + $dateAgent->format('d.m.Y H:i:s'), + 30 + ); + + $APPLICATION->RestartBuffer(); + header('Content-Type: application/x-javascript; charset=' . LANG_CHARSET); + die(json_encode(['success' => true])); +} + $availableSites = RetailcrmConfigProvider::getSitesList(); if (!empty($availableSites)) { @@ -1269,6 +1290,7 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { $version = COption::GetOptionString($mid, $CRM_API_VERSION, 0); + $optionsFixDateCustomer = COption::GetOptionString($mid, RetailcrmConstants::OPTION_FIX_DATE_CUSTOMER, 0); // Old functional $currencyOption = COption::GetOptionString($mid, $CRM_CURRENCY, 0) ?: CCurrency::GetBaseCurrency(); @@ -1562,7 +1584,11 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { matchedElement.querySelector(`select[name=${crmName}`).setAttribute("name", crmName + "_" + nextId); matchedElement.removeAttribute("hidden"); - document.getElementById(type + "_matched").appendChild(matchedElement); + let element = document.getElementById(type + "_matched"); + + if (element) { + element.appendChild(matchedElement); + } } function deleteMatched(element) @@ -2879,7 +2905,29 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { if ($(this).is(':checked')) { alert(''); } - }); + }); + + function customerFixDate() { + var handleUrl = $('#fix-upload_customer').attr('action'); + var data = 'ajax=3'; + + $.ajax({ + type: 'POST', + url: handleUrl, + data: data, + dataType: 'json', + success: function () { + $('#block-fix-customer-date').html("

"); + }, + error: function () { + $('#block-fix-customer-date').html("

"); + } + }) + } + + $('input[name="start-fix-date-customer"]').on('click', function () { + customerFixDate(); + }); }); @@ -3416,6 +3464,21 @@ if (isset($_POST['Update']) && ($_POST['Update'] === 'Y')) { + + + + + + + +

+ + + + + + + Buttons(); ?>