Primer commit del sistema separado falta mejorar mucho

This commit is contained in:
nickpons666
2025-12-30 01:18:46 -06:00
commit 1679c73e52
2384 changed files with 472342 additions and 0 deletions

View File

@@ -0,0 +1,93 @@
<?php
/**
* API de Plantillas de Telegram - Crear
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Autenticación
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para crear plantillas de Telegram.']);
exit;
}
// Solo permitir método POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
// Obtener datos
$data = json_decode(file_get_contents('php://input'), true);
$nombre = trim($data['nombre'] ?? '');
$comando = trim($data['comando'] ?? '');
$contenido = $data['contenido'] ?? '';
// Validación
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido de la plantilla son obligatorios.']);
exit;
}
try {
$db = getDB();
// Verificar si el comando ya existe (si se proporcionó)
if ($comando) {
$stmt = $db->prepare("SELECT id FROM plantillas_telegram WHERE comando = ?");
$stmt->execute([$comando]);
if ($stmt->fetch()) {
http_response_code(409); // 409 Conflict
echo json_encode(['success' => false, 'error' => 'Ya existe una plantilla con ese comando.']);
exit;
}
}
// Insertar en la base de datos
$stmt = $db->prepare("
INSERT INTO plantillas_telegram (nombre, comando, contenido, usuario_id, fecha_creacion, fecha_modificacion)
VALUES (?, ?, ?, ?, NOW(), NOW())
");
$stmt->execute([
$nombre,
empty($comando) ? null : $comando,
$contenido,
$userData->userId
]);
$newTemplateId = $db->lastInsertId();
logToFile('telegram/templates.log', "Plantilla creada: {$nombre} (ID: {$newTemplateId}), Usuario: {$userData->username}");
echo json_encode([
'success' => true,
'message' => 'Plantilla creada correctamente.',
'templateId' => $newTemplateId
]);
} catch (Exception $e) {
http_response_code(500);
error_log('Error en /telegram/api/templates/create.php: ' . $e->getMessage());
echo json_encode(['success' => false, 'error' => 'Error del servidor al guardar la plantilla.']);
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* API - Eliminar plantilla Telegram
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Verificar autenticación
if (!isAuthenticated()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para eliminar plantillas de Telegram.']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405);
}
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['id'])) {
jsonResponse(['success' => false, 'error' => 'ID no proporcionado'], 400);
}
try {
$db = getDB();
// Verificar que la plantilla existe
$stmt = $db->prepare("SELECT * FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$input['id']]);
$plantilla = $stmt->fetch();
if (!$plantilla) {
jsonResponse(['success' => false, 'error' => 'Plantilla no encontrada'], 404);
}
// Verificar permisos (admin o creador)
if ($userData->rol !== 'Admin' && $plantilla['usuario_id'] != $userData->userId) {
jsonResponse(['success' => false, 'error' => 'No tiene permisos para eliminar esta plantilla'], 403);
}
// Eliminar plantilla
$stmt = $db->prepare("DELETE FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$input['id']]);
logToFile('telegram/templates.log', "Plantilla eliminada: ID={$input['id']}, Usuario={$userData->username}");
jsonResponse(['success' => true, 'message' => 'Plantilla eliminada correctamente']);
} catch (Exception $e) {
logToFile('telegram/errors.log', "Error eliminando plantilla: " . $e->getMessage(), 'ERROR');
jsonResponse(['success' => false, 'error' => 'Error del servidor'], 500);
}

115
telegram/api/templates/edit.php Executable file
View File

@@ -0,0 +1,115 @@
<?php
/**
* API de Plantillas de Telegram - Editar
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Autenticación
try {
$userData = JWTAuth::requireAuth();
} catch (Exception $e) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado: ' . $e->getMessage()]);
exit;
}
// Verificar permiso
if (!hasPermission('manage_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para editar plantillas de Telegram.']);
exit;
}
// Solo permitir método POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
// Obtener datos
$data = json_decode(file_get_contents('php://input'), true);
$id = $data['id'] ?? null;
$nombre = trim($data['nombre'] ?? '');
$comando = trim($data['comando'] ?? '');
$contenido = $data['contenido'] ?? '';
// Validación
if (!$id || !is_numeric($id)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'ID de plantilla inválido o no proporcionado.']);
exit;
}
if (empty($nombre) || empty($contenido)) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => 'El nombre y el contenido de la plantilla son obligatorios.']);
exit;
}
try {
$db = getDB();
// Obtener la plantilla actual para verificar permisos
$stmt = $db->prepare("SELECT usuario_id FROM plantillas_telegram WHERE id = ?");
$stmt->execute([$id]);
$plantillaExistente = $stmt->fetch();
if (!$plantillaExistente) {
http_response_code(404);
echo json_encode(['success' => false, 'error' => 'Plantilla no encontrada.']);
exit;
}
// Verificar permisos: solo Admin o el propietario pueden editar
if ($userData->rol !== 'Admin' && $plantillaExistente['usuario_id'] != $userData->userId) {
http_response_code(403); // Forbidden
echo json_encode(['success' => false, 'error' => 'No tiene permisos para editar esta plantilla.']);
exit;
}
// Verificar si el comando ya existe (excepto para la plantilla actual)
if (!empty($comando)) {
$stmt = $db->prepare("SELECT id FROM plantillas_telegram WHERE comando = ? AND id != ?");
$stmt->execute([$comando, $id]);
if ($stmt->fetch()) {
http_response_code(409); // Conflict
echo json_encode(['success' => false, 'error' => 'Ya existe otra plantilla con ese comando.']);
exit;
}
}
// Actualizar en la base de datos
$stmt = $db->prepare("
UPDATE plantillas_telegram
SET nombre = ?, comando = ?, contenido = ?, fecha_modificacion = NOW()
WHERE id = ?
");
$stmt->execute([
$nombre,
empty($comando) ? null : $comando,
$contenido,
$id
]);
logToFile('telegram/templates.log', "Plantilla editada: ID={$id}, por Usuario: {$userData->username}");
echo json_encode([
'success' => true,
'message' => 'Plantilla actualizada correctamente.'
]);
} catch (Exception $e) {
http_response_code(500);
logToFile('telegram/errors.log', 'Error editando plantilla: ' . $e->getMessage(), 'ERROR');
echo json_encode(['success' => false, 'error' => 'Ocurrió un error en el servidor al actualizar la plantilla.']);
}

64
telegram/api/templates/list.php Executable file
View File

@@ -0,0 +1,64 @@
<?php
/**
* API de Plantillas de Telegram - Listar
*/
header('Content-Type: application/json');
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';
// Para depuración
ini_set('display_errors', 0);
error_reporting(E_ALL);
// Verificar autenticación
if (!isAuthenticated()) {
http_response_code(401);
echo json_encode(['success' => false, 'error' => 'No autenticado']);
exit;
}
// Verificar permiso
if (!hasPermission('view_templates', 'telegram')) {
http_response_code(403);
echo json_encode(['success' => false, 'error' => 'No tienes permiso para ver las plantillas de Telegram.']);
exit;
}
try {
$db = getDB();
// Búsqueda (opcional, para futuras mejoras)
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sql = "
SELECT p.id, p.nombre, p.comando, p.fecha_modificacion, u.username
FROM plantillas_telegram p
LEFT JOIN usuarios u ON p.usuario_id = u.id
";
$params = [];
if (!empty($search)) {
$sql .= " WHERE p.nombre LIKE ? OR p.comando LIKE ?";
$params[] = "%{$search}%";
$params[] = "%{$search}%";
}
$sql .= " ORDER BY p.fecha_modificacion DESC";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$templates = $stmt->fetchAll();
echo json_encode([
'success' => true,
'templates' => $templates
]);
} catch (Exception $e) {
http_response_code(500);
error_log('Error en /telegram/api/templates/list.php: ' . $e->getMessage());
echo json_encode(['success' => false, 'error' => 'Error del servidor al obtener las plantillas.']);
}