]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Настройки и проверки очередей
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 5 Dec 2024 08:47:05 +0000 (11:47 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 5 Dec 2024 08:47:05 +0000 (11:47 +0300)
erp24/composer.json
erp24/config/console.php
erp24/config/web.php
erp24/controllers/TgController.php
erp24/jobs/SendTelegramMessageJob.php [new file with mode: 0644]
erp24/services/TelegramService.php
erp24/views/tg/send-message.php [new file with mode: 0644]

index d8d2dae388fb3963327865d8fb9bf41bba06f9c5..aede880ef81d30fb83fcf5c3cada717e9a390e57 100644 (file)
@@ -34,7 +34,9 @@
         "kartik-v/yii2-grid": "@dev",
         "kartik-v/yii2-widget-datepicker": "dev-master",
         "phpoffice/phpspreadsheet": "^2.2",
-        "ext-xmlreader": "*"
+        "ext-xmlreader": "*",
+        "enqueue/amqp-lib": "^0.10.19"
+
     },
     "require-dev": {
         "yiisoft/yii2-debug": "~2.1.0",
@@ -53,7 +55,8 @@
         "yiisoft/yii2-bootstrap": "~2.0.0",
         "2amigos/yii2-date-time-picker-widget" : "*",
         "2amigos/yii2-date-picker-widget" : "~1.0",
-        "2amigos/qrcode-library": "^2.0"
+        "2amigos/qrcode-library": "^2.0",
+        "squizlabs/php_codesniffer": "@stable"
     },
     "autoload": {
         "psr-4": { "OpenAPI\\Client\\" : "lib/yandex_market_api/" }
index d75b8bf4060edba94bf74eafc1c761db60116be2..a4874e0adbcb4ad7d8b32cd5e3ec700f46b4a91a 100755 (executable)
@@ -1,5 +1,8 @@
 <?php
 
+
+use yii\queue\amqp_interop\Queue;
+
 $params = require __DIR__ . '/params.php';
 
 Yii::setAlias('@yii_app/commands', 'commands');
@@ -8,8 +11,8 @@ Yii::setAlias('@yii_app', dirname(__DIR__));
 $config = [
     'id' => 'basic-console',
     'basePath' => dirname(__DIR__),
-    'bootstrap' => ['log'],
-//    'bootstrap' => ['log', 'queue'],
+//    'bootstrap' => ['log'],
+    'bootstrap' => ['log', 'queue'],
     'controllerNamespace' => 'yii_app\commands',
     'aliases' => [
         '@bower' => '@vendor/bower-asset',
@@ -37,6 +40,13 @@ $config = [
 //            'channel' => 'default',
 //            'mutex' => \yii\mutex\MysqlMutex::class,
 //        ],
+        'queue' => [
+            'class' => Queue::class,
+            'dsn' => 'amqp://admin:admin@rabbitmq-yii_erp24:5672',
+            'queueName' => 'queue-name',
+            'as log' => \yii\queue\LogBehavior::class,
+
+        ],
         'cache' => [
             'class' => 'yii\caching\FileCache',
         ],
index b4a1b6a8f351480ceeaace69b26acee4adbe9d85..294229230528ca938fdf12713e2b295c1105f430 100644 (file)
@@ -1,12 +1,14 @@
 <?php
 
+use yii\queue\amqp_interop\Queue;
+
 $params = require __DIR__ . '/params.php';
 $db = require __DIR__ . '/db.php';
 
 $config = [
     'id' => 'basic',
     'basePath' => dirname(__DIR__),
-    'bootstrap' => ['log'],
+    'bootstrap' => ['log', 'queue'],
     'aliases' => [
         '@bower' => '@vendor/bower-asset',
         '@npm' => '@vendor/npm-asset',
@@ -37,6 +39,13 @@ $config = [
             // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
             'cookieValidationKey' => 'Z0uKu8AtuwGTVD_qX4inPOe1xq3FdWcV',
         ],
+        'queue' => [
+            'class' => Queue::class,
+            'dsn' => 'amqp://admin:admin@rabbitmq-yii_erp24:5672',
+            'queueName' => 'queue-name',
+            'as log' => \yii\queue\LogBehavior::class,
+
+        ],
         'cache' => [
             'class' => 'yii\caching\FileCache',
         ],
index 61750e04ab35fe4b3807063e62f1547efafd6d18..7cf91f35e433d5bf4f2fc519bd1134e158756520 100644 (file)
@@ -2,7 +2,9 @@
 
 namespace app\controllers;
 
+use Yii;
 use yii\web\Controller;
+use app\jobs\SendTelegramMessageJob;
 
 class TgController extends Controller
 {
@@ -12,4 +14,38 @@ class TgController extends Controller
             'subscription' => \yii_app\actions\tg\SubscriptionAction::class,
         ];
     }
-}
\ No newline at end of file
+
+    public function actionSendMessage()
+    {
+        $request = Yii::$app->request;
+
+        // Массив с ID чатов (в будущем можно заменить на запрос из базы данных)
+        $chatIds = [
+            '730432579', // Chat ID 1
+            '6207259989', // Chat ID 2
+            ];
+
+        if ($request->isPost) {
+            $data = $request->post('DynamicModel');
+            $message = $data['message'] ?? null;
+
+            if ($message) {
+                Yii::$app->session->setFlash('success', 'Сообщение отправлено!');
+            } else {
+                Yii::$app->session->setFlash('error', 'Сообщение не может быть пустым!');
+            }
+
+            foreach ($chatIds as $chatId) {
+                Yii::$app->queue->push(new SendTelegramMessageJob([
+                    'chatId' => $chatId,
+                    'message' => $message,
+                ]));
+            }
+
+            Yii::$app->session->setFlash('success', 'Сообщение добавлено в очередь для всех чатов.');
+            return $this->redirect(['send-message']);
+        }
+
+        return $this->render('send-message');
+    }
+}
diff --git a/erp24/jobs/SendTelegramMessageJob.php b/erp24/jobs/SendTelegramMessageJob.php
new file mode 100644 (file)
index 0000000..9ada0fe
--- /dev/null
@@ -0,0 +1,18 @@
+<?php
+
+namespace app\jobs;
+
+
+use yii_app\services\TelegramService;
+
+class SendTelegramMessageJob extends \yii\base\BaseObject implements \yii\queue\JobInterface
+{
+    public $chatId;
+    public $message;
+
+    public function execute($queue)
+    {
+        $telegramService = new TelegramService();
+        $telegramService->sendMessageToTelegramClient($this->chatId, $this->message);
+    }
+}
\ No newline at end of file
index 1b0ab9c98ba3b6b993c52b88ff6b0b40fc1e56d0..ede0a91215689291e930f779ffdb74e31cdab597 100644 (file)
@@ -5,15 +5,18 @@ namespace yii_app\services;
 use GuzzleHttp\Client;
 use Yii;
 
-class TelegramService {
+class TelegramService
+{
 
 
     const TELEGRAM_API_URL = "8063257458:AAGnMf4cxwJWlYLF1wS_arn4PrOaLs9ERQQ";
 
     const TARGET_PROD_URL = "erp.erp-flowers.ru";
-    const CHAT_CHANNEL_ID ="-1001861631125";
-    const CHAT_CHANNEL_ERP_ID ="-1002338329426";
-    public static function sendMessage($admin_id, $message, $reply_markup = null) {
+    const CHAT_CHANNEL_ID = "-1001861631125";
+    const CHAT_CHANNEL_ERP_ID = "-1002338329426";
+
+    public static function sendMessage($admin_id, $message, $reply_markup = null)
+    {
         $url = "https://api2.bazacvetov24.ru/telegram/send-message?admin_id=$admin_id&message=$message";
         if ($reply_markup) {
             $url .= "&reply_markup=" . json_encode($reply_markup, JSON_UNESCAPED_UNICODE);
@@ -22,46 +25,69 @@ class TelegramService {
         return $client->request('GET', $url);
     }
 
-     public static function isDevelopmentEnvironment($urlString = null) : bool
-     {
-         $currentUrl = empty($urlString) ? Yii::$app->request->getHostInfo() : $urlString;
-         return !str_contains($currentUrl, self::TARGET_PROD_URL);
-     }
+    public static function isDevelopmentEnvironment($urlString = null): bool
+    {
+        $currentUrl = empty($urlString) ? Yii::$app->request->getHostInfo() : $urlString;
+        return !str_contains($currentUrl, self::TARGET_PROD_URL);
+    }
 
-public static function sendErrorToTelegramMessage($message,$disableNotification, $isDev)
-{
-    $botToken = self::TELEGRAM_API_URL;
-    $chatIdDefault = self::CHAT_CHANNEL_ID;
-    $chatIdErp = self::CHAT_CHANNEL_ERP_ID;
-    $apiURL = "https://api.telegram.org/bot{$botToken}/sendMessage";
+    public static function sendErrorToTelegramMessage($message, $disableNotification, $isDev)
+    {
+        $botToken = self::TELEGRAM_API_URL;
+        $chatIdDefault = self::CHAT_CHANNEL_ID;
+        $chatIdErp = self::CHAT_CHANNEL_ERP_ID;
+        $apiURL = "https://api.telegram.org/bot{$botToken}/sendMessage";
 
 
-    if ($isDev) {
-        $chatId = $chatIdDefault;
-    } else  {
-        $chatId = $chatIdErp;
+        if ($isDev) {
+            $chatId = $chatIdDefault;
+        } else {
+            $chatId = $chatIdErp;
+        }
+
+        $client = new Client();
+        try {
+            $client->post($apiURL, [
+                'json' => [
+                    'chat_id' => $chatId,
+                    'text' => $message,
+                    'parse_mode' => 'MarkdownV2',
+                    'disable_notification' => $disableNotification,
+                ],
+            ]);
+        } catch (\Exception $e) {
+            Yii::error("Ошибка отправки сообщения в Telegram: " . $e->getMessage(), 'telegram');
+        }
     }
 
-    $client = new Client();
-    try {
-        $client->post($apiURL, [
-            'json' => [
-                'chat_id' => $chatId,
-                'text' => $message,
-                'parse_mode' => 'MarkdownV2',
-                'disable_notification' => $disableNotification,
-            ],
-        ]);
-    } catch (\Exception $e) {
-        Yii::error("Ошибка отправки сообщения в Telegram: " . $e->getMessage(), 'telegram');
+    public static function sendMessageToTelegramClient($chatId, $message)
+    {
+        $botToken = self::TELEGRAM_API_URL; // Токен вашего Telegram-бота
+        $apiURL = "https://api.telegram.org/bot{$botToken}/sendMessage";
+
+        $client = new Client();
+        try {
+            $response = $client->post($apiURL, [
+                'json' => [
+                    'chat_id' => $chatId,
+                    'text' => $message,
+                    'parse_mode' => 'MarkdownV2',
+                ],
+            ]);
+
+            if ($response->getStatusCode() !== 200) {
+                Yii::error("Ошибка при отправке сообщения в Telegram. Код ответа: "
+                    . $response->getStatusCode(), 'telegram');
+            }
+        } catch (\Exception $e) {
+            Yii::error("Ошибка отправки сообщения в Telegram: " . $e->getMessage(), 'telegram');
+        }
     }
-}
 
 
     // Метод для экранирования символов MarkdownV2 для файла
     public static function escapeMarkdown($text)
     {
-
         $specialChars = ['_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!'];
 
         foreach ($specialChars as $char) {
diff --git a/erp24/views/tg/send-message.php b/erp24/views/tg/send-message.php
new file mode 100644 (file)
index 0000000..ee40a97
--- /dev/null
@@ -0,0 +1,38 @@
+<?php
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+
+$this->title = 'Отправить сообщение в Telegram';
+?>
+
+<div class="send-message-form">
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <?php if (Yii::$app->session->hasFlash('success')): ?>
+        <div class="alert alert-success">
+            <?= Yii::$app->session->getFlash('success') ?>
+        </div>
+    <?php elseif (Yii::$app->session->hasFlash('error')): ?>
+        <div class="alert alert-danger">
+            <?= Yii::$app->session->getFlash('error') ?>
+        </div>
+    <?php endif; ?>
+
+    <?php $form = ActiveForm::begin([
+        'action' => ['tg/send-message'], // Путь к экшену
+        'method' => 'post',
+    ]); ?>
+
+    <?= $form->field(new \yii\base\DynamicModel(['message']), 'message')
+        ->textarea([
+            'rows' => 3,
+            'placeholder' => 'Введите сообщение для отправки',
+        ])
+        ->label('Сообщение') ?>
+
+    <div class="form-group">
+        <?= Html::submitButton('Отправить сообщение', ['class' => 'btn btn-primary']) ?>
+    </div>
+
+    <?php ActiveForm::end(); ?>
+</div>
\ No newline at end of file