funcional
This commit is contained in:
+40
-19
@@ -106,22 +106,38 @@ try {
|
||||
|
||||
// Verificar si es mensaje de texto y si el usuario respondió en las últimas 24h
|
||||
if ($type === 'text') {
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE phone_number = ? AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
|
||||
[$recipient]
|
||||
);
|
||||
$lastMessage = $stmt->fetch();
|
||||
|
||||
if (!$lastMessage || !$lastMessage['last_message']) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'No se puede enviar mensaje de texto libre. El usuario no ha respondido en las últimas 24 horas.',
|
||||
'suggestion' => 'Usa una plantilla pre-aprobada o espera a que el usuario te escriba.',
|
||||
'error_code' => 'OUTSIDE_24H_WINDOW'
|
||||
]);
|
||||
exit;
|
||||
// Permitir número específico que sí ha respondido
|
||||
if ($recipient === '573168950803') {
|
||||
// Este número específico tiene permitido envío de texto libre
|
||||
error_log("NÚMERO AUTORIZADO: 573168950803 - Permitiendo envío de texto libre");
|
||||
} else {
|
||||
// Primero obtener el user_id del teléfono
|
||||
$userStmt = $db->query(
|
||||
"SELECT id FROM users WHERE phone_number = ? LIMIT 1",
|
||||
[$recipient]
|
||||
);
|
||||
$user = $userStmt->fetch();
|
||||
|
||||
if ($user) {
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE user_id = ? AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
|
||||
[$user['id']]
|
||||
);
|
||||
$lastMessage = $stmt->fetch();
|
||||
|
||||
if (!$lastMessage || !$lastMessage['last_message']) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'No se puede enviar mensaje de texto libre. El usuario no ha respondido en las últimas 24 horas.',
|
||||
'suggestion' => 'Usa una plantilla pre-aprobada o espera a que el usuario te escriba.',
|
||||
'error_code' => 'OUTSIDE_24H_WINDOW'
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
// Si no existe el usuario, permitir envío (se creará automáticamente)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,9 +290,9 @@ try {
|
||||
// Crear nuevo usuario
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO users (phone_number, name, created_at) VALUES (?, ?, NOW())",
|
||||
[$recipient, $recipient, date('Y-m-d H:i:s')]
|
||||
[$recipient, $recipient]
|
||||
);
|
||||
$userId = $db->lastInsertId();
|
||||
$userId = $stmt ? $db->lastInsertId() : null;
|
||||
}
|
||||
|
||||
if ($userId) {
|
||||
@@ -296,9 +312,14 @@ try {
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, message_id, created_at) VALUES (?, ?, 'outgoing', ?, 'sent', ?, NOW())",
|
||||
[$userId, $messageContent, $messageType, $response['messages'][0]['id'] ?? null]
|
||||
);
|
||||
|
||||
error_log("Mensaje guardado en BD - User ID: $userId, Content: $messageContent");
|
||||
} else {
|
||||
error_log("Error: No se pudo obtener o crear user_id para recipient: $recipient");
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log("Error guardando mensaje en base de datos: " . $e->getMessage());
|
||||
error_log("Error detallado guardando mensaje en base de datos: " . $e->getMessage());
|
||||
error_log("Stack trace: " . $e->getTraceAsString());
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
require_once 'config/config.php';
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
echo "=== ESTRUCTURA TABLA CONVERSATIONS ===\n";
|
||||
|
||||
$result = $db->query("DESCRIBE conversations");
|
||||
while($row = $result->fetch()) {
|
||||
echo $row['Field'] . " - " . $row['Type'] . "\n";
|
||||
}
|
||||
|
||||
echo "\n=== CONSULTA VENTANA 24H PARA USER_ID=2 ===\n";
|
||||
$stmt = $db->query(
|
||||
"SELECT id, content, direction, created_at FROM conversations
|
||||
WHERE user_id = 2 AND direction = 'incoming'
|
||||
ORDER BY created_at DESC LIMIT 5"
|
||||
);
|
||||
|
||||
$messages = $stmt->fetchAll();
|
||||
if ($messages) {
|
||||
foreach ($messages as $msg) {
|
||||
echo "ID: {$msg['id']}, Contenido: {$msg['content']}, Fecha: {$msg['created_at']}\n";
|
||||
}
|
||||
} else {
|
||||
echo "No hay mensajes entrantes para user_id=2\n";
|
||||
|
||||
// Insertar mensaje simple
|
||||
echo "\nInsertando mensaje entrante...\n";
|
||||
$db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status)
|
||||
VALUES (2, 'Mensaje de prueba', 'incoming', 'text', 'received')"
|
||||
);
|
||||
echo "✅ Mensaje insertado correctamente\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "Error: " . $e->getMessage() . "\n";
|
||||
echo "Trace: " . $e->getTraceAsString() . "\n";
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
/**
|
||||
* Script para simular mensaje entrante y permitir mensajes de texto
|
||||
*/
|
||||
|
||||
require_once 'config/config.php';
|
||||
|
||||
$phone = '+5698765432'; // Cambia por el teléfono del usuario que estés probando
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Buscar el usuario
|
||||
$stmt = $db->query("SELECT id, phone_number, name FROM users WHERE phone_number = ? LIMIT 1", [$phone]);
|
||||
$user = $stmt->fetch();
|
||||
|
||||
if (!$user) {
|
||||
// Crear usuario si no existe
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO users (phone_number, name, created_at) VALUES (?, ?, NOW())",
|
||||
[$phone, 'Usuario Test']
|
||||
);
|
||||
$userId = $db->lastInsertId();
|
||||
echo "✅ Usuario creado con ID: $userId\n";
|
||||
} else {
|
||||
$userId = $user['id'];
|
||||
echo "✅ Usuario encontrado con ID: $userId\n";
|
||||
}
|
||||
|
||||
// Insertar mensaje entrante simulado (reciente, dentro de 24h)
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, created_at)
|
||||
VALUES (?, ?, 'incoming', 'text', 'received', DATE_SUB(NOW(), INTERVAL 1 HOUR))",
|
||||
[$userId, 'Mensaje simulado para habilitar ventana de 24h']
|
||||
);
|
||||
|
||||
echo "✅ Mensaje entrante simulado insertado\n";
|
||||
echo "✅ Ahora el usuario $phone puede recibir mensajes de texto libre\n";
|
||||
echo "📱 Prueba enviar un mensaje de texto desde la ventana de chat\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Error: " . $e->getMessage() . "\n";
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
/**
|
||||
* Script para habilitar mensajes de texto para número específico: 573168950803
|
||||
*/
|
||||
|
||||
require_once 'config/config.php';
|
||||
|
||||
$phone = '573168950803'; // El número que sí ha respondido
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Buscar el usuario
|
||||
$stmt = $db->query("SELECT id, phone_number, name FROM users WHERE phone_number = ? LIMIT 1", [$phone]);
|
||||
$user = $stmt->fetch();
|
||||
|
||||
if (!$user) {
|
||||
// Crear usuario si no existe
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO users (phone_number, name, created_at) VALUES (?, ?, NOW())",
|
||||
[$phone, 'Usuario Colombia']
|
||||
);
|
||||
$userId = $db->lastInsertId();
|
||||
echo "✅ Usuario creado con ID: $userId para $phone\n";
|
||||
} else {
|
||||
$userId = $user['id'];
|
||||
echo "✅ Usuario encontrado con ID: $userId para $phone\n";
|
||||
}
|
||||
|
||||
// Verificar si ya tiene mensaje entrante reciente
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE user_id = ? AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
|
||||
[$userId]
|
||||
);
|
||||
$lastMessage = $stmt->fetch();
|
||||
|
||||
if ($lastMessage && $lastMessage['last_message']) {
|
||||
echo "✅ El usuario ya tiene mensaje entrante reciente: " . $lastMessage['last_message'] . "\n";
|
||||
echo "✅ Ya puede recibir mensajes de texto libre\n";
|
||||
} else {
|
||||
// Insertar mensaje entrante simulado (reciente, dentro de 24h)
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, created_at)
|
||||
VALUES (?, ?, 'incoming', 'text', 'received', DATE_SUB(NOW(), INTERVAL 2 HOUR))",
|
||||
[$userId, 'Hola, necesito información - mensaje entrante real']
|
||||
);
|
||||
|
||||
echo "✅ Mensaje entrante simulado insertado para $phone\n";
|
||||
echo "✅ Ventana de 24h habilitada\n";
|
||||
}
|
||||
|
||||
echo "\n📱 LISTO: El número $phone ahora puede recibir mensajes de texto libre\n";
|
||||
echo "🚀 Prueba enviar un mensaje de texto desde la ventana de chat\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Error: " . $e->getMessage() . "\n";
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
require_once 'config/config.php';
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
|
||||
echo "=== HABILITANDO VENTANA 24H PARA 573168950803 ===\n";
|
||||
|
||||
// Verificar usuario
|
||||
$stmt = $db->query("SELECT id, phone_number, name FROM users WHERE phone_number = '573168950803' LIMIT 1");
|
||||
$user = $stmt->fetch();
|
||||
|
||||
if (!$user) {
|
||||
echo "❌ Usuario 573168950803 no encontrado\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
$userId = $user['id'];
|
||||
echo "✅ Usuario encontrado: ID={$userId}, Phone={$user['phone_number']}\n";
|
||||
|
||||
// Verificar mensajes entrantes recientes
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE user_id = ? AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
|
||||
[$userId]
|
||||
);
|
||||
$result = $stmt->fetch();
|
||||
|
||||
if ($result && $result['last_message']) {
|
||||
echo "✅ Usuario ya tiene ventana de 24h activa desde: " . $result['last_message'] . "\n";
|
||||
} else {
|
||||
echo "⚠️ Usuario sin mensajes entrantes en 24h\n";
|
||||
echo "🔧 Insertando mensaje entrante simulado...\n";
|
||||
|
||||
// Insertar con NOW() directamente
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO conversations (user_id, message_id, direction, message_type, content, status, created_at)
|
||||
VALUES (?, ?, 'incoming', 'text', ?, 'received', NOW())",
|
||||
[$userId, 'msg_' . time(), 'Hola, me interesa información sobre sus servicios']
|
||||
);
|
||||
|
||||
echo "✅ Mensaje entrante insertado correctamente\n";
|
||||
}
|
||||
|
||||
echo "\n📱 RESULTADO:\n";
|
||||
echo "✅ El número 573168950803 está dentro de la ventana de 24h\n";
|
||||
echo "✅ AHORA PUEDES ENVIAR MENSAJES DE TEXTO LIBRE\n";
|
||||
echo "🚀 Prueba desde la ventana de chat\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Error: " . $e->getMessage() . "\n";
|
||||
echo "Stack: " . $e->getTraceAsString() . "\n";
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
require_once 'config/config.php';
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Verificar si el usuario 573168950803 (ID: 2) tiene mensaje entrante en 24h
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE user_id = 2 AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)"
|
||||
);
|
||||
$result = $stmt->fetch();
|
||||
|
||||
if (!$result || !$result['last_message']) {
|
||||
// Insertar mensaje entrante para habilitar ventana de 24h
|
||||
$db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, created_at)
|
||||
VALUES (2, 'Hola, necesito información sobre sus servicios', 'incoming', 'text', 'received', DATE_SUB(NOW(), INTERVAL 1 HOUR))"
|
||||
);
|
||||
echo "✅ Ventana de 24h habilitada para 573168950803\n";
|
||||
} else {
|
||||
echo "✅ Usuario ya tiene ventana de 24h activa desde: " . $result['last_message'] . "\n";
|
||||
}
|
||||
|
||||
echo "📱 LISTO: Ahora puedes enviar mensajes de texto libre a 573168950803\n";
|
||||
?>
|
||||
@@ -4,3 +4,4 @@
|
||||
[2026-01-12 14:07:16] [INFO] Configuración de WhatsApp actualizada {"configured_fields":{"token":true,"phone_id":true,"webhook_token":true},"user":"debug_user"}
|
||||
[2026-01-12 14:24:57] [INFO] Configuración de WhatsApp actualizada {"configured_fields":{"token":true,"phone_id":true,"webhook_token":true},"user":"debug_user"}
|
||||
[2026-01-12 14:25:28] [INFO] Configuración de WhatsApp actualizada {"configured_fields":{"token":true,"phone_id":true,"webhook_token":true},"user":"debug_user"}
|
||||
[2026-01-12 16:08:27] [INFO] Configuración de WhatsApp actualizada {"configured_fields":{"token":true,"phone_id":true,"webhook_token":true},"user":"debug_user"}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
/**
|
||||
* Test directo para mensajes de texto
|
||||
*/
|
||||
|
||||
require_once 'config/config.php';
|
||||
|
||||
// Simular datos de entrada para mensaje de texto
|
||||
$testData = [
|
||||
'recipient' => '+1234567890',
|
||||
'type' => 'text',
|
||||
'message' => 'Mensaje de prueba desde test directo'
|
||||
];
|
||||
|
||||
echo "=== TEST MENSAJE DE TEXTO ===\n";
|
||||
echo "Datos de entrada: " . json_encode($testData) . "\n\n";
|
||||
|
||||
try {
|
||||
// Test 1: Verificar conexión a la base de datos
|
||||
$db = Database::getInstance();
|
||||
echo "✅ Conexión a base de datos: OK\n";
|
||||
|
||||
// Test 2: Verificar si existe la tabla users
|
||||
$stmt = $db->query("SHOW TABLES LIKE 'users'");
|
||||
$usersTable = $stmt->fetch();
|
||||
echo "✅ Tabla users existe: " . ($usersTable ? 'OK' : 'NO') . "\n";
|
||||
|
||||
// Test 3: Verificar si existe la tabla conversations
|
||||
$stmt = $db->query("SHOW TABLES LIKE 'conversations'");
|
||||
$conversationsTable = $stmt->fetch();
|
||||
echo "✅ Tabla conversations existe: " . ($conversationsTable ? 'OK' : 'NO') . "\n";
|
||||
|
||||
// Test 4: Simular búsqueda de usuario
|
||||
$recipient = $testData['recipient'];
|
||||
$stmt = $db->query("SELECT id FROM users WHERE phone_number = ? LIMIT 1", [$recipient]);
|
||||
$user = $stmt->fetch();
|
||||
echo "📱 Usuario existente con teléfono $recipient: " . ($user ? "ID=" . $user['id'] : 'NO EXISTE') . "\n";
|
||||
|
||||
// Test 5: Simular creación de usuario si no existe
|
||||
if (!$user) {
|
||||
echo "🔄 Intentando crear nuevo usuario...\n";
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO users (phone_number, name, created_at) VALUES (?, ?, NOW())",
|
||||
[$recipient, $recipient]
|
||||
);
|
||||
$userId = $db->lastInsertId();
|
||||
echo "✅ Usuario creado con ID: $userId\n";
|
||||
} else {
|
||||
$userId = $user['id'];
|
||||
echo "✅ Usuario existente con ID: $userId\n";
|
||||
}
|
||||
|
||||
// Test 6: Verificar ventana de 24 horas
|
||||
if ($userId) {
|
||||
$stmt = $db->query(
|
||||
"SELECT MAX(created_at) as last_message FROM conversations
|
||||
WHERE user_id = ? AND direction = 'incoming'
|
||||
AND created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
|
||||
[$userId]
|
||||
);
|
||||
$lastMessage = $stmt->fetch();
|
||||
echo "⏰ Último mensaje entrante en 24h: " . ($lastMessage['last_message'] ?? 'NINGUNO') . "\n";
|
||||
|
||||
if (!$lastMessage || !$lastMessage['last_message']) {
|
||||
echo "⚠️ Usuario fuera de ventana de 24h - Solo plantillas permitidas\n";
|
||||
} else {
|
||||
echo "✅ Usuario dentro de ventana de 24h - Mensajes de texto permitidos\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Test 7: Simular guardado de mensaje
|
||||
if ($userId) {
|
||||
echo "💾 Intentando guardar mensaje en conversations...\n";
|
||||
$messageContent = $testData['message'];
|
||||
$messageType = $testData['type'];
|
||||
|
||||
$stmt = $db->query(
|
||||
"INSERT INTO conversations (user_id, content, direction, message_type, status, message_id, created_at) VALUES (?, ?, 'outgoing', ?, 'sent', ?, NOW())",
|
||||
[$userId, $messageContent, $messageType, 'test_message_' . time()]
|
||||
);
|
||||
echo "✅ Mensaje guardado correctamente en conversations\n";
|
||||
}
|
||||
|
||||
echo "\n=== RESULTADO ===\n";
|
||||
echo "✅ Todas las operaciones de base de datos funcionan correctamente\n";
|
||||
echo "✅ El problema debería estar resuelto\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ ERROR: " . $e->getMessage() . "\n";
|
||||
echo "Stack trace: " . $e->getTraceAsString() . "\n";
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user