]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Перенос настроек
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 7 Mar 2025 08:43:23 +0000 (11:43 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 7 Mar 2025 08:43:23 +0000 (11:43 +0300)
erp24/commands/CronController.php
erp24/controllers/UsersMessageManagementController.php
erp24/jobs/SendWhatsappMessageJob.php
erp24/records/UsersMessageManagement.php
erp24/services/WhatsAppService.php

index a95b366a7cbf6a6457f0752f500388c3ce193df9..f277ea902c9af215f3d99f0c574a25c47005f9b7 100644 (file)
@@ -2,7 +2,7 @@
 
 namespace yii_app\commands;
 
-use app\jobs\SendTelegramMessageDBJob;
+
 use app\jobs\SendTelegramMessageJob;
 use app\jobs\SendWhatsappMessageJob;
 use DateTime;
@@ -12,14 +12,8 @@ use yii\console\Controller;
 use yii\console\ExitCode;
 use yii\db\Expression;
 use yii\helpers\BaseConsole;
-use yii\helpers\Console;
 use yii_app\helpers\ClientHelper;
 use yii_app\records\BonusLevels;
-use yii_app\records\EqualizationRemains;
-use yii_app\records\Product1cReplacement;
-use yii_app\records\Products1c;
-use yii_app\records\ReplacementInvoice;
-use yii_app\records\ReplacementInvoiceProducts;
 use yii_app\records\Sales;
 use yii_app\records\SentKogort;
 use yii_app\records\Users;
@@ -766,9 +760,8 @@ class CronController extends Controller
                 BaseConsole::FG_GREEN
             );
 
-            $channel = WhatsAppService::getChannelByName('WABA');
-            $limit = $channel['messagingLimit'] ?? 250;
-
+            $limit =  $messagesSettings ? $messagesSettings->channel_limit : 250;
+            $cascadeId = $messagesSettings ? $messagesSettings->cascade_id : 5686;
             $salesData = Sales::find()
                 ->select([
                     'phone',
@@ -807,6 +800,7 @@ class CronController extends Controller
                     $messageData['kogort_date'] = $kogortDate;
                     $messageData['target_date'] = $targetDate;
                     $messageData['message'] = $messageText;
+                    $messageData['cascade_id'] = $cascadeId;
 
                     Yii::$app->queue->push(new SendWhatsappMessageJob([
                         'messageData' => $messageData,
index 97fbc85ed334880464601730fe586cbc0d2f3361..33e9b6e240c642f759adbf4d82e32ab8cd98eb3a 100644 (file)
@@ -23,6 +23,7 @@ use yii_app\records\UsersMessageManagement;
 use yii_app\records\UsersMessageManagementLogs;
 use yii_app\records\UsersTelegram;
 use yii_app\records\UsersTelegramLog;
+use yii_app\services\WhatsAppService;
 
 class UsersMessageManagementController extends Controller
 {
@@ -108,7 +109,35 @@ class UsersMessageManagementController extends Controller
             $model->updated_at = date('Y-m-d H:i:s');
             $model->updated_by = Yii::$app->user->id;
             if ($model->validate()) {
+                if (!empty($model->channel_name)) {
+                    $channelData = WhatsappService::getChannelByName($model->channel_name);
+                    if (!empty($channelData)) {
+                        if (isset($channelData['subjectId'])) {
+                            $model->subject_id = $channelData['subjectId'];
+                        }
+                        if (isset($channelData['messagingLimit'])) {
+                            $model->channel_limit = $channelData['messagingLimit'];
+                        }
+                    }
+                }
+
+                if (!empty($model->cascade_name)) {
+                    $cascadeId = WhatsappService::getCascadeIdByName($model->cascade_name);
+                    if ($cascadeId) {
+                        $model->cascade_id = $cascadeId;
+                    }
+                }
 
+                if (!empty($model->subject_id) && !empty($model->template_name)) {
+                    $templateId = WhatsappService::getMessageMatcherIdBySubjectId(
+                        $model->subject_id,
+                        $model->template_name,
+                        ["OPERATOR", "USER", "CUSTOM"]
+                    );
+                    if ($templateId) {
+                        $model->template_id = $templateId;
+                    }
+                }
                 $model->save();
                 $newAttributes = $model->getAttributes();
                 self::saveLogs($oldAttributes, $newAttributes);
index 8b0faffa31b92c32dff4f3691f7ab4b65e82edda..65cce5b8eb984cb2ddd5c53c7718b610c99ba94a 100644 (file)
@@ -47,21 +47,20 @@ class SendWhatsappMessageJob extends BaseObject implements JobInterface
         }
 
         $phone = $this->messageData['phone'];
-
+        $isTest = $this->isTest;
+        $message  = ($this->messageData)['message'];
+        $kogortDate = ($this->messageData)['kogort_date'];
+        $targetDate = ($this->messageData)['target_date'];
         $apiKey    = Yii::$app->params['WHATSAPP_API_KEY'];
-        $cascadeId = WhatsAppService::getCascadeIdByName('WABA') ?? 5686;
-        $whatsappService = new WhatsAppService($apiKey, $cascadeId);
+        $cascadeId = ($this->messageData)['cascade_id'];
         $requestId = DataHelper::uuid();
+        $whatsappService = new WhatsAppService($apiKey, $cascadeId);
+
         try {
-            $isTest = $this->isTest;
-            $message  = ($this->messageData)['message'];
-            $kogortDate = ($this->messageData)['kogort_date'];
-            $targetDate = ($this->messageData)['target_date'];
-            if ($this->isTest) {
-                $message   = "Здравствуйте\nУзнать подробности вы можете на нашем сайте https://bazacvetov24.ru.";
+            if (!$this->isTest) {
+               // $message   = "Здравствуйте\nУзнать подробности вы можете на нашем сайте https://bazacvetov24.ru.";
+                $response = $whatsappService->sendMessage($requestId, $phone, $message, $isTest);
             }
-            $response = $whatsappService->sendMessage($requestId, $phone, $message, $isTest);
-
 
             $status = 'sent';
             if (!$response instanceof WhatsAppMessageResponse) {
@@ -77,10 +76,25 @@ class SendWhatsappMessageJob extends BaseObject implements JobInterface
             $record->created_at = date('Y-m-d H:i:s');
 
             if ($record->save()) {
-                Yii::warning("WhatsApp сообщение успешно отправлено и сохранено для телефона {$phone}. Request ID: " .
-                    $response->requestId, 'whatsapp');
+                if (!$this->isTest) {
+                    Yii::warning(
+                        "WhatsApp сообщение успешно отправлено и сохранено для телефона {$phone}. Request ID: " .
+                        $response->requestId,
+                        'whatsapp'
+                    );
+                } else {
+                    Yii::warning(
+                        "WhatsApp сообщение успешно сохранено для телефона {$phone}. Request ID: " .
+                        $requestId,
+                        'whatsapp'
+                    );
+                }
             } else {
-                Yii::warning("WhatsApp сообщение отправлено, но не удалось сохранить запись для телефона {$phone}." . json_encode($record->getErrors(), JSON_UNESCAPED_UNICODE), 'whatsapp');
+                Yii::warning(
+                    "WhatsApp сообщение отправлено, но не удалось сохранить запись для телефона {$phone}."
+                    . json_encode($record->getErrors(), JSON_UNESCAPED_UNICODE),
+                    'whatsapp'
+                );
             }
         } catch (\Exception $e) {
             Yii::error("Ошибка отправки WhatsApp сообщения для телефона {$phone}: " . $e->getMessage(), 'whatsapp');
index 542dfc6838e63481fd92502563ffd204178012ac..6ffad82e508c32cb14f31b6e3465a40d548e1fcd 100644 (file)
@@ -33,6 +33,14 @@ use Yii;
  * @property string $test_phones_list Список тестовых телефонов
  * @property string $test_phones_active Активность тестового списка
  * @property string $channel_name Имя канала
+ * @property string $channel_id Идентификатор канала - подпись
+ * @property string $channel_limit Суточный лимит сообщений
+ * @property string $cascade_name Имя каскада
+ * @property string $cascade_id ID каскада
+ * @property string $subject_id Идентификатор подписи
+ * @property string $template_name Имя шаблона
+ * @property string $template_id Идентификатор шаблона
+ * @property string $callback_status_url URL приема колбеков статусов сообщений
  */
 class UsersMessageManagement extends \yii\db\ActiveRecord
 {
index 14f277cc91dfc4332037107fe2d165b54fa76bc1..357cfd4cbf1c13a5e050f48509cd202f061730e0 100644 (file)
@@ -137,8 +137,9 @@ class WhatsAppService
             Yii::error("Текст сообщения для WhatsApp не передан.");
             return null;
         }
-        $channel = self::getChannelByName('WABA');
-        $subjectId = $channel['subjectId'] ?? 11374;
+        $messagesSettings = UsersMessageManagement::find()->one();
+
+        $subjectId = $messagesSettings ? $messagesSettings->cascade_id : 5686;
 
         $requestId = $requestId ?? DataHelper::uuid();
         // Формируем фильтр получателя по номеру телефона
@@ -148,7 +149,7 @@ class WhatsAppService
         ];
 
         $buttons =  [
-            'rows' => [
+            'row' => [
                     'buttons' => [
                         [
                             'text'       => 'Наш сайт',
@@ -170,13 +171,15 @@ class WhatsAppService
         ];
 
         if (!$isTest) {
-           // $whatsappContent['keyboard'] = $buttons;
-            $whatsappContent['messageMatcherId'] = self::getMessageMatcherIdBySubjectId($subjectId, 'kogort_message_3') ?? 121254;
+            $whatsappContent['messageMatcherId'] = $messagesSettings ? $messagesSettings->template_id : 121254;
         } else {
-            $whatsappContent['messageMatcherId'] = self::getMessageMatcherIdBySubjectId($subjectId, 'podrobnosti') ?? 117216;
+            $whatsappContent['keyboard'] = $buttons;
+            $whatsappContent['messageMatcherId'] = self::getMessageMatcherIdBySubjectId(
+                $subjectId,
+                'kogort_message'
+            ) ?? 120669;
         }
 
-
         $payload = [
             'requestId'        => $requestId,
             'cascadeId'        => $this->cascadeId,