Integração com Telegram

This commit is contained in:
Halbe Bruno
2025-12-05 21:20:31 -03:00
parent 1e761ea3d8
commit 81dd696d0b
8 changed files with 409 additions and 0 deletions

View File

@@ -4,6 +4,7 @@ namespace App\Controllers;
use App\Models\Order;
use App\Services\OrderProcessor;
use App\Services\TelegramService;
use App\Utils\View;
class OrderController
@@ -99,6 +100,16 @@ class OrderController
$processor = new OrderProcessor();
$count = $processor->process($orderId, $type, $_FILES['csv_file']['tmp_name']);
// Send Telegram Notification
$telegramService = new TelegramService();
$typeLabel = ($type === 'block') ? 'Bloqueio' : (($type === 'unblock') ? 'Desbloqueio' : $type);
$telegramService->sendOrderNotification([
'id' => $orderId,
'title' => $title,
'type' => $typeLabel
], $count);
$_SESSION['flash_success'] = "Ordem criada com sucesso! $count domínios processados.";
View::redirect('/admin/orders');

View File

@@ -0,0 +1,58 @@
<?php
namespace App\Controllers;
use App\Models\Setting;
use App\Services\TelegramService;
use App\Utils\View;
class SettingsController
{
public function index()
{
$settingModel = new Setting();
$settings = $settingModel->getAll();
View::render('layouts.admin', [
'title' => 'Configurações',
'content' => __DIR__ . '/../../resources/views/admin/settings/index.php',
'settings' => $settings
]);
}
public function update()
{
$settingModel = new Setting();
foreach ($_POST as $key => $value) {
$settingModel->set($key, $value);
}
$_SESSION['flash_success'] = "Configurações atualizadas com sucesso!";
View::redirect('/admin/settings');
}
public function testTelegram()
{
header('Content-Type: application/json');
$telegramService = new TelegramService();
// Use sendOrderNotification to test with the configured template
$response = $telegramService->sendOrderNotification([
'id' => '12345',
'title' => 'Teste de Integração',
'type' => 'Teste'
], 999);
$result = json_decode($response, true);
if ($result && isset($result['ok']) && $result['ok']) {
echo json_encode(['success' => true, 'message' => 'Mensagem enviada com sucesso!']);
} else {
$error = $result['description'] ?? 'Erro desconhecido ao contatar API do Telegram.';
echo json_encode(['success' => false, 'message' => 'Falha ao enviar: ' . $error]);
}
exit;
}
}

45
app/Models/Setting.php Normal file
View File

@@ -0,0 +1,45 @@
<?php
namespace App\Models;
use App\Core\Model;
class Setting extends Model
{
protected $table = 'settings';
protected $primaryKey = 'key';
public function get($key, $default = null)
{
$stmt = $this->conn->prepare("SELECT value FROM {$this->table} WHERE `key` = :key");
$stmt->execute(['key' => $key]);
$result = $stmt->fetch();
return $result ? $result['value'] : $default;
}
public function set($key, $value)
{
// Check if exists
if ($this->get($key) !== null) {
$stmt = $this->conn->prepare("UPDATE {$this->table} SET value = :value WHERE `key` = :key");
} else {
$stmt = $this->conn->prepare("INSERT INTO {$this->table} (`key`, value) VALUES (:key, :value)");
}
return $stmt->execute(['key' => $key, 'value' => $value]);
}
public function getAll()
{
$stmt = $this->conn->query("SELECT * FROM {$this->table}");
$results = $stmt->fetchAll();
$settings = [];
foreach ($results as $row) {
$settings[$row['key']] = $row['value'];
}
return $settings;
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace App\Services;
use App\Models\Setting;
class TelegramService
{
private $token;
private $chatId;
private $settingModel;
public function __construct()
{
$this->settingModel = new Setting();
$this->token = $this->settingModel->get('telegram_bot_token');
$this->chatId = $this->settingModel->get('telegram_chat_id');
}
public function sendMessage($message)
{
if (empty($this->token) || empty($this->chatId)) {
return false;
}
$url = "https://api.telegram.org/bot{$this->token}/sendMessage";
$data = [
'chat_id' => $this->chatId,
'text' => $message,
'parse_mode' => 'HTML'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public function sendOrderNotification($order, $domainCount)
{
$template = $this->settingModel->get('telegram_message_template');
if (empty($template)) {
$template = "<b>Nova Ordem Cadastrada!</b>\n\n<b>Título:</b> {title}\n<b>Tipo:</b> {type}\n<b>Domínios:</b> {total_domains}";
}
$message = str_replace(
['{title}', '{type}', '{total_domains}', '{order_id}'],
[$order['title'], $order['type'], $domainCount, $order['id']],
$template
);
return $this->sendMessage($message);
}
}

View File

@@ -43,6 +43,11 @@ $router->get('/admin/orders/create', [\App\Controllers\OrderController::class, '
$router->post('/admin/orders/store', [\App\Controllers\OrderController::class, 'store']);
$router->get('/admin/orders/view/{id}', [\App\Controllers\OrderController::class, 'view']);
// Settings
$router->get('/admin/settings', [\App\Controllers\SettingsController::class, 'index']);
$router->post('/admin/settings/update', [\App\Controllers\SettingsController::class, 'update']);
$router->post('/admin/settings/test-telegram', [\App\Controllers\SettingsController::class, 'testTelegram']);
$router->addMiddleware(\App\Middleware\AdminMiddleware::class);
// API Routes

View File

@@ -0,0 +1,23 @@
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use App\Config\Database;
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
try {
$conn = Database::getInstance()->getConnection();
$sql = "CREATE TABLE IF NOT EXISTS settings (
`key` VARCHAR(255) PRIMARY KEY,
`value` TEXT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;";
$conn->exec($sql);
echo "Tabela 'settings' criada com sucesso!" . PHP_EOL;
} catch (PDOException $e) {
echo "Erro ao criar tabela: " . $e->getMessage() . PHP_EOL;
}

View File

@@ -0,0 +1,193 @@
<div x-data="settings">
<!-- Tabs Header -->
<div class="border-b border-gray-200 mb-6">
<nav class="-mb-px flex space-x-8" aria-label="Tabs">
<button @click="activeTab = 'interactions'"
:class="activeTab === 'interactions' ? 'border-primary-500 text-primary-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-colors">
Interações
</button>
</nav>
</div>
<!-- Interactions Tab -->
<div x-show="activeTab === 'interactions'" x-transition:enter="transition ease-out duration-200"
x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-sm border border-gray-100 p-6">
<h3 class="text-lg font-semibold text-gray-800 mb-6">Telegram</h3>
<p class="text-sm text-gray-500 mb-6">Configure as notificações automáticas para o Telegram.</p>
<form action="/admin/settings/update" method="POST">
<div class="space-y-4">
<!-- Bot Token -->
<div>
<label for="telegram_bot_token" class="block text-sm font-medium text-gray-700 mb-1">Bot
Token</label>
<input type="text" name="telegram_bot_token" id="telegram_bot_token"
value="<?= htmlspecialchars($settings['telegram_bot_token'] ?? '') ?>"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="123456789:ABCdefGHIjklMNOpqRSTuvwXYZ">
<p class="mt-1 text-sm text-gray-500">O token fornecido pelo @BotFather.</p>
</div>
<!-- Chat ID -->
<div>
<label for="telegram_chat_id" class="block text-sm font-medium text-gray-700 mb-1">Chat
ID</label>
<input type="text" name="telegram_chat_id" id="telegram_chat_id"
value="<?= htmlspecialchars($settings['telegram_chat_id'] ?? '') ?>"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="-1001234567890">
<p class="mt-1 text-sm text-gray-500">ID do canal ou grupo para onde as mensagens serão
enviadas.</p>
</div>
<!-- Message Template -->
<div>
<label for="telegram_message_template"
class="block text-sm font-medium text-gray-700 mb-1">Modelo de Mensagem</label>
<textarea id="telegram_message_template" name="telegram_message_template" rows="5"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
placeholder="Nova ordem cadastrada!"><?= htmlspecialchars($settings['telegram_message_template'] ?? "<b>Nova Ordem Cadastrada!</b>\n\n<b>Título:</b> {title}\n<b>Tipo:</b> {type}\n<b>Domínios:</b> {total_domains}") ?></textarea>
<p class="mt-2 text-sm text-gray-500">
Variáveis disponíveis: <code class="bg-gray-100 px-1 rounded">{title}</code>,
<code class="bg-gray-100 px-1 rounded">{type}</code>,
<code class="bg-gray-100 px-1 rounded">{total_domains}</code>,
<code class="bg-gray-100 px-1 rounded">{order_id}</code>.
Suporta HTML (negrito, itálico, etc).
</p>
</div>
</div>
<div class="mt-6 flex justify-end space-x-3">
<button type="button" @click="testIntegration()" :disabled="testing"
class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center">
<svg x-show="testing" class="animate-spin -ml-1 mr-3 h-5 w-5 text-gray-700"
xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
</circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
<span x-text="testing ? 'Enviando...' : 'Testar Integração'"></span>
</button>
<button type="submit"
class="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors">
Salvar Configurações
</button>
</div>
</form>
</div>
</div>
<!-- Notification Toast -->
<div x-show="notification.show" x-transition:enter="transition ease-out duration-300"
x-transition:enter-start="opacity-0 transform translate-y-2"
x-transition:enter-end="opacity-100 transform translate-y-0"
x-transition:leave="transition ease-in duration-200"
x-transition:leave-start="opacity-100 transform translate-y-0"
x-transition:leave-end="opacity-0 transform translate-y-2"
class="fixed bottom-4 right-4 z-50 max-w-sm w-full bg-white shadow-lg rounded-lg pointer-events-auto ring-1 ring-black ring-opacity-5 overflow-hidden">
<div class="p-4">
<div class="flex items-start">
<div class="flex-shrink-0">
<svg x-show="notification.type === 'success'" class="h-6 w-6 text-green-400" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<svg x-show="notification.type === 'error'" class="h-6 w-6 text-red-400" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div class="ml-3 w-0 flex-1 pt-0.5">
<p class="text-sm font-medium text-gray-900" x-text="notification.title"></p>
<p class="mt-1 text-sm text-gray-500" x-text="notification.message"></p>
</div>
<div class="ml-4 flex-shrink-0 flex">
<button @click="notification.show = false"
class="bg-white rounded-md inline-flex text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
<span class="sr-only">Fechar</span>
<svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clip-rule="evenodd" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('settings', () => ({
activeTab: 'interactions',
testing: false,
notification: {
show: false,
type: 'success',
title: '',
message: ''
},
testIntegration() {
this.testing = true;
// Save settings first via AJAX if needed, but for now we assume saved settings
// Or we could send form data. Let's send form data to ensure we test what's typed.
const form = document.querySelector('form');
const formData = new FormData(form);
// We need to update settings first?
// The requirement implies testing the configuration.
// Usually "Test" uses the saved config or the current input.
// Let's assume we test the SAVED config for simplicity as per plan,
// but user might expect to test what they just typed.
// To be safe and robust: Update settings then test, OR send values to test endpoint.
// The plan said "instantiate TelegramService" which uses DB.
// So the user must SAVE first.
// Let's warn if inputs are dirty? Too complex for now.
// Let's just call the endpoint.
fetch('/admin/settings/test-telegram', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(data => {
this.showNotification(
data.success ? 'success' : 'error',
data.success ? 'Sucesso' : 'Erro',
data.message
);
})
.catch(error => {
this.showNotification('error', 'Erro', 'Falha na requisição.');
})
.finally(() => {
this.testing = false;
});
},
showNotification(type, title, message) {
this.notification.type = type;
this.notification.title = title;
this.notification.message = message;
this.notification.show = true;
setTimeout(() => {
this.notification.show = false;
}, 5000);
}
}))
})
</script>

View File

@@ -122,6 +122,19 @@
</nav>
<div class="p-4 border-t border-gray-100">
<a href="/admin/settings"
class="flex items-center px-4 py-3 text-gray-600 rounded-lg hover:bg-primary-50 hover:text-primary-700 transition-colors group <?= (strpos($_SERVER['REQUEST_URI'], '/admin/settings') !== false) ? 'bg-primary-50 text-primary-700' : '' ?>">
<svg class="w-5 h-5 mr-3 group-hover:text-primary-500" fill="none" stroke="currentColor"
viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z">
</path>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z">
</path>
</svg>
Configurações
</a>
<a href="/logout"
class="flex items-center px-4 py-3 text-gray-600 rounded-lg hover:bg-red-50 hover:text-red-700 transition-colors">
<svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">