todo funcional

This commit is contained in:
lizandrogd
2026-01-12 22:58:19 -05:00
parent 01c30ca594
commit 7afde9573f
7 changed files with 1060 additions and 81 deletions
+70
View File
@@ -0,0 +1,70 @@
<?php
/**
* API - Eliminar respuesta automática
* Fecha: 12 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: DELETE, POST');
header('Access-Control-Allow-Headers: Content-Type');
try {
$id = null;
// Obtener ID desde diferentes fuentes
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_GET['id'] ?? null;
} else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['id'] ?? $_POST['id'] ?? null;
}
if (!$id) {
throw new Exception('ID de respuesta automática requerido');
}
$id = intval($id);
if ($id <= 0) {
throw new Exception('ID de respuesta automática no válido');
}
$db = Database::getInstance();
// Verificar que existe
$existing = $db->fetchAll("SELECT id, trigger_type, trigger_value FROM autoresponses WHERE id = ?", [$id]);
if (empty($existing)) {
throw new Exception('Respuesta automática no encontrada');
}
// Eliminar
$deleted = $db->execute("DELETE FROM autoresponses WHERE id = ?", [$id]);
if ($deleted) {
echo json_encode([
'success' => true,
'message' => 'Respuesta automática eliminada correctamente',
'deleted_id' => $id,
'deleted_data' => $existing[0]
]);
} else {
throw new Exception('No se pudo eliminar la respuesta automática');
}
} catch (Exception $e) {
error_log("Error en delete_autoresponse.php: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
'debug' => $e->getTraceAsString()
]);
}
?>
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* API - Obtener respuestas automáticas
* Fecha: 12 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Content-Type');
try {
$db = Database::getInstance();
// Verificar si la tabla existe, si no crearla
$tablesExist = $db->fetchAll("SHOW TABLES LIKE 'autoresponses'");
if (empty($tablesExist)) {
error_log("Creando tabla autoresponses...");
$createAutoResponsesSQL = "CREATE TABLE IF NOT EXISTS autoresponses (
id INT AUTO_INCREMENT PRIMARY KEY,
trigger_type ENUM('keyword', 'contains', 'exact', 'welcome', 'default') NOT NULL DEFAULT 'keyword',
trigger_value TEXT,
response_text TEXT NOT NULL,
response_type ENUM('text', 'template', 'menu') NOT NULL DEFAULT 'text',
template_name VARCHAR(255),
menu_id INT,
priority INT DEFAULT 0,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_trigger_type (trigger_type),
INDEX idx_is_active (is_active),
INDEX idx_priority (priority)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
$db->execute($createAutoResponsesSQL);
// Crear respuestas automáticas de ejemplo
$exampleResponses = [
[
'trigger_type' => 'welcome',
'trigger_value' => null,
'response_text' => '¡Hola! 👋 Bienvenido a nuestro servicio. ¿En qué puedo ayudarte?',
'response_type' => 'text',
'priority' => 10,
'is_active' => 1
],
[
'trigger_type' => 'keyword',
'trigger_value' => 'hola,buenos días,buenas tardes,buenas noches,hi,hello',
'response_text' => '¡Hola! 😊 Gracias por contactarnos. ¿En qué podemos ayudarte hoy?',
'response_type' => 'text',
'priority' => 5,
'is_active' => 1
],
[
'trigger_type' => 'keyword',
'trigger_value' => 'precio,precios,costo,costos,cuanto cuesta,tarifa',
'response_text' => '💰 Para información sobre precios, por favor visita nuestro sitio web o contacta directamente con nuestro equipo de ventas.',
'response_type' => 'text',
'priority' => 3,
'is_active' => 1
],
[
'trigger_type' => 'keyword',
'trigger_value' => 'horario,horarios,abierto,cerrado,cuando abren',
'response_text' => '🕒 Nuestros horarios de atención son:\nLunes a Viernes: 9:00 AM - 6:00 PM\nSábados: 9:00 AM - 2:00 PM\nDomingos: Cerrado',
'response_type' => 'text',
'priority' => 3,
'is_active' => 1
],
[
'trigger_type' => 'default',
'trigger_value' => null,
'response_text' => 'Gracias por tu mensaje. Un representante se pondrá en contacto contigo pronto. 🤝',
'response_type' => 'text',
'priority' => 1,
'is_active' => 1
]
];
foreach ($exampleResponses as $response) {
$db->insert('autoresponses', $response);
}
error_log("Tabla autoresponses creada con datos de ejemplo");
}
// Obtener todas las respuestas automáticas
$autoresponses = $db->fetchAll(
"SELECT * FROM autoresponses ORDER BY priority DESC, created_at DESC"
);
echo json_encode([
'success' => true,
'data' => $autoresponses,
'total' => count($autoresponses),
'message' => 'Respuestas automáticas cargadas correctamente'
]);
} catch (Exception $e) {
error_log("Error en get_autoresponses.php: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Error interno del servidor',
'debug' => $e->getMessage(),
'data' => []
]);
}
?>
+120 -23
View File
@@ -1,11 +1,14 @@
<?php
/**
* API - Obtener logs del webhook
* Fecha: 13 de noviembre de 2025
* API - Obtener logs del sistema
* Fecha: 12 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
@@ -14,31 +17,125 @@ header('Access-Control-Allow-Headers: Content-Type');
try {
$db = Database::getInstance();
$limit = $_GET['limit'] ?? 50;
$offset = $_GET['offset'] ?? 0;
$limit = intval($_GET['limit'] ?? 50);
$offset = intval($_GET['offset'] ?? 0);
$type = $_GET['type'] ?? 'system'; // 'system' o 'webhook'
$logs = $db->fetchAll(
"SELECT
id,
status_code,
ip_address,
created_at,
SUBSTRING(request_body, 1, 100) as request_preview,
SUBSTRING(response_body, 1, 100) as response_preview
FROM webhook_logs
ORDER BY created_at DESC
LIMIT :limit OFFSET :offset",
[
'limit' => (int)$limit,
'offset' => (int)$offset
]
);
if ($limit > 100) $limit = 100; // Máximo 100 registros
echo json_encode($logs);
// Verificar qué tablas existen
$existingTables = $db->fetchAll("SHOW TABLES");
$tableNames = array_column($existingTables, 'Tables_in_' . DB_NAME);
$logs = [];
if ($type === 'webhook' && in_array('webhook_logs', $tableNames)) {
// Logs de webhook (formato original)
$logs = $db->fetchAll(
"SELECT
id,
status_code,
ip_address,
created_at,
SUBSTRING(request_body, 1, 100) as request_preview,
SUBSTRING(response_body, 1, 100) as response_preview,
'webhook' as source,
'INFO' as level,
CONCAT('Webhook request - Status: ', COALESCE(status_code, 'N/A')) as message
FROM webhook_logs
ORDER BY created_at DESC
LIMIT ? OFFSET ?",
[$limit, $offset]
);
} else {
// Logs del sistema
if (!in_array('system_logs', $tableNames)) {
// Crear tabla de logs del sistema
$createLogsSQL = "CREATE TABLE IF NOT EXISTS system_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
datetime DATETIME DEFAULT CURRENT_TIMESTAMP,
level ENUM('ERROR', 'WARNING', 'INFO', 'DEBUG', 'SUCCESS') DEFAULT 'INFO',
message TEXT NOT NULL,
source VARCHAR(255) DEFAULT 'Sistema',
data JSON,
user_id INT,
ip_address VARCHAR(45),
user_agent TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_datetime (datetime),
INDEX idx_level (level),
INDEX idx_source (source)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
$db->execute($createLogsSQL);
// Insertar logs de ejemplo
$exampleLogs = [
[
'level' => 'INFO',
'message' => 'Sistema de WhatsApp Bot iniciado correctamente',
'source' => 'Sistema',
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
],
[
'level' => 'SUCCESS',
'message' => 'Módulo de respuestas automáticas cargado',
'source' => 'AutoResponse',
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
],
[
'level' => 'INFO',
'message' => 'Sistema de menús inicializado',
'source' => 'MenuSystem',
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
],
[
'level' => 'WARNING',
'message' => 'Verificar configuración de tokens WhatsApp',
'source' => 'Config',
'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
]
];
foreach ($exampleLogs as $log) {
$db->insert('system_logs', $log);
}
}
$logs = $db->fetchAll(
"SELECT
id,
datetime,
level,
message,
source,
data,
ip_address,
created_at
FROM system_logs
ORDER BY datetime DESC, id DESC
LIMIT ? OFFSET ?",
[$limit, $offset]
);
}
echo json_encode([
'success' => true,
'data' => $logs,
'total' => count($logs),
'type' => $type,
'message' => 'Logs cargados correctamente'
]);
} catch (Exception $e) {
error_log("Error in get_logs.php: " . $e->getMessage());
error_log("Error en get_logs.php: " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 'Error interno del servidor']);
echo json_encode([
'success' => false,
'error' => 'Error interno del servidor',
'debug' => $e->getMessage(),
'data' => []
]);
}
?>
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* API - Guardar respuesta automática
* Fecha: 12 de enero de 2026
*/
require_once '../config/config.php';
// Verificar autenticación
requireAuthentication();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
// Solo permitir POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
exit;
}
try {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
throw new Exception('Datos no válidos');
}
// Validar campos requeridos
$required_fields = ['trigger_type', 'response_text'];
foreach ($required_fields as $field) {
if (!isset($input[$field]) || trim($input[$field]) === '') {
throw new Exception("El campo '$field' es requerido");
}
}
$db = Database::getInstance();
// Preparar datos para insertar/actualizar
$data = [
'trigger_type' => $input['trigger_type'],
'response_text' => trim($input['response_text']),
'response_type' => $input['response_type'] ?? 'text',
'priority' => intval($input['priority'] ?? 0),
'is_active' => isset($input['is_active']) ? (bool)$input['is_active'] : true,
'updated_at' => date('Y-m-d H:i:s')
];
// Campos opcionales
if (!empty($input['trigger_value'])) {
$data['trigger_value'] = trim($input['trigger_value']);
}
if (!empty($input['template_name'])) {
$data['template_name'] = trim($input['template_name']);
}
if (!empty($input['menu_id'])) {
$data['menu_id'] = intval($input['menu_id']);
}
// Verificar si es actualización o inserción
if (!empty($input['id'])) {
// Actualización
$id = intval($input['id']);
// Verificar que existe
$existing = $db->fetchAll("SELECT id FROM autoresponses WHERE id = ?", [$id]);
if (empty($existing)) {
throw new Exception('Respuesta automática no encontrada');
}
// Actualizar
$setClauses = [];
$values = [];
foreach ($data as $key => $value) {
$setClauses[] = "$key = ?";
$values[] = $value;
}
$values[] = $id;
$sql = "UPDATE autoresponses SET " . implode(', ', $setClauses) . " WHERE id = ?";
$db->execute($sql, $values);
$message = 'Respuesta automática actualizada correctamente';
} else {
// Inserción
$data['created_at'] = date('Y-m-d H:i:s');
$id = $db->insert('autoresponses', $data);
$message = 'Respuesta automática creada correctamente';
}
// Obtener el registro actualizado/creado
$autoresponse = $db->fetchAll("SELECT * FROM autoresponses WHERE id = ?", [$id]);
echo json_encode([
'success' => true,
'data' => $autoresponse[0] ?? null,
'message' => $message,
'id' => $id
]);
} catch (Exception $e) {
error_log("Error en save_autoresponse.php: " . $e->getMessage());
http_response_code(500);
echo json_encode([
'success' => false,
'error' => $e->getMessage(),
'debug' => $e->getTraceAsString()
]);
}
?>