From: fomichev Date: Thu, 5 Dec 2024 08:47:05 +0000 (+0300) Subject: Настройки и проверки очередей X-Git-Tag: 1.7~67^2~12^2~3 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=dda7915aa9427ad823feb5e4faf9d1603e5d8306;p=erp24_rep%2Fyii-erp24%2F.git Настройки и проверки очередей --- diff --git a/erp24/composer.json b/erp24/composer.json index d8d2dae3..aede880e 100644 --- a/erp24/composer.json +++ b/erp24/composer.json @@ -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/" } diff --git a/erp24/config/console.php b/erp24/config/console.php index d75b8bf4..a4874e0a 100755 --- a/erp24/config/console.php +++ b/erp24/config/console.php @@ -1,5 +1,8 @@ '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', ], diff --git a/erp24/config/web.php b/erp24/config/web.php index b4a1b6a8..29422923 100644 --- a/erp24/config/web.php +++ b/erp24/config/web.php @@ -1,12 +1,14 @@ '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', ], diff --git a/erp24/controllers/TgController.php b/erp24/controllers/TgController.php index 61750e04..7cf91f35 100644 --- a/erp24/controllers/TgController.php +++ b/erp24/controllers/TgController.php @@ -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 index 00000000..9ada0fed --- /dev/null +++ b/erp24/jobs/SendTelegramMessageJob.php @@ -0,0 +1,18 @@ +sendMessageToTelegramClient($this->chatId, $this->message); + } +} \ No newline at end of file diff --git a/erp24/services/TelegramService.php b/erp24/services/TelegramService.php index 1b0ab9c9..ede0a912 100644 --- a/erp24/services/TelegramService.php +++ b/erp24/services/TelegramService.php @@ -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 index 00000000..ee40a97b --- /dev/null +++ b/erp24/views/tg/send-message.php @@ -0,0 +1,38 @@ +title = 'Отправить сообщение в Telegram'; +?> + +
+

title) ?>

+ + session->hasFlash('success')): ?> +
+ session->getFlash('success') ?> +
+ session->hasFlash('error')): ?> +
+ session->getFlash('error') ?> +
+ + + ['tg/send-message'], // Путь к экшену + 'method' => 'post', + ]); ?> + + field(new \yii\base\DynamicModel(['message']), 'message') + ->textarea([ + 'rows' => 3, + 'placeholder' => 'Введите сообщение для отправки', + ]) + ->label('Сообщение') ?> + +
+ 'btn btn-primary']) ?> +
+ + +
\ No newline at end of file