Files
MVE/debug_templates.php
2025-10-21 11:41:30 -06:00

196 lines
7.8 KiB
PHP

<?php
// Script de debug simple para templates
session_start();
// Para debugging, vamos a simular una sesión válida
if (!isset($_SESSION['usuario_id'])) {
$_SESSION['usuario_id'] = 1; // Cambia este valor por tu ID de usuario real
$_SESSION['id_agencia_en_uso'] = 1; // Cambia por tu ID de agencia real
}
require_once __DIR__ . '/config/database.php';
echo "<h2>🔍 Debug Simple de Templates</h2>";
echo "<p><strong>Usuario actual:</strong> " . $_SESSION['usuario_id'] . "</p>";
echo "<p><strong>Agencia actual:</strong> " . ($_SESSION['id_agencia_en_uso'] ?? 'NULL') . "</p>";
try {
$conn = getConnection();
// 1. Ver todos los templates sin filtros
echo "<h3>1. Todos los templates en la base de datos:</h3>";
$sql = "SELECT id, nombre, descripcion, activo, id_usuario_creador, id_agencia,
fecha_creacion, config_json
FROM dbo.templates_rapidos
ORDER BY fecha_creacion DESC";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
$errors = sqlsrv_errors();
echo "<div style='color: red;'>❌ Error en consulta: " . print_r($errors, true) . "</div>";
} else {
$count = 0;
echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
echo "<tr style='background: #f0f0f0;'>
<th>ID</th>
<th>Nombre</th>
<th>Descripción</th>
<th>Activo</th>
<th>Usuario Creador</th>
<th>Agencia</th>
<th>Fecha Creación</th>
<th>Tiene Config</th>
</tr>";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$count++;
$fecha = $row['fecha_creacion'] instanceof DateTime
? $row['fecha_creacion']->format('Y-m-d H:i:s')
: $row['fecha_creacion'];
$tieneConfig = !empty($row['config_json']) ? 'Sí' : 'No';
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td><strong>" . htmlspecialchars($row['nombre']) . "</strong></td>";
echo "<td>" . htmlspecialchars($row['descripcion'] ?? '') . "</td>";
echo "<td>" . ($row['activo'] ? '✅' : '❌') . "</td>";
echo "<td>" . ($row['id_usuario_creador'] ?? 'NULL') . "</td>";
echo "<td>" . ($row['id_agencia'] ?? 'NULL') . "</td>";
echo "<td>" . $fecha . "</td>";
echo "<td>" . $tieneConfig . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<p><strong>Total de templates encontrados: $count</strong></p>";
}
// 2. Probar la consulta exacta del endpoint
echo "<h3>2. Probando consulta del endpoint (con filtros):</h3>";
$id_usuario = $_SESSION['usuario_id'];
$id_agencia = $_SESSION['id_agencia_en_uso'];
$sql_endpoint = "SELECT id, nombre, descripcion, icono, config_json,
ISNULL(veces_usado, 0) as veces_usado,
id_usuario_creador, id_agencia
FROM dbo.templates_rapidos
WHERE activo = 1
AND (id_usuario_creador = ? OR id_agencia = ? OR id_agencia IS NULL)
ORDER BY
CASE WHEN id_usuario_creador = ? THEN 0 ELSE 1 END,
veces_usado DESC,
nombre ASC";
$stmt_endpoint = sqlsrv_query($conn, $sql_endpoint, [$id_usuario, $id_agencia, $id_usuario]);
if ($stmt_endpoint === false) {
$errors = sqlsrv_errors();
echo "<div style='color: red;'>❌ Error en consulta endpoint: " . print_r($errors, true) . "</div>";
} else {
$count_endpoint = 0;
echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
echo "<tr style='background: #e3f2fd;'>
<th>ID</th>
<th>Nombre</th>
<th>Es Mío</th>
<th>Usuario Creador</th>
<th>Agencia</th>
<th>Debería Aparecer</th>
</tr>";
while ($row = sqlsrv_fetch_array($stmt_endpoint, SQLSRV_FETCH_ASSOC)) {
$count_endpoint++;
$esMio = ($row['id_usuario_creador'] == $id_usuario) ? 'SÍ' : 'NO';
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td><strong>" . htmlspecialchars($row['nombre']) . "</strong></td>";
echo "<td style='color: " . ($esMio === 'SÍ' ? 'green' : 'blue') . ";'><strong>$esMio</strong></td>";
echo "<td>" . ($row['id_usuario_creador'] ?? 'NULL') . "</td>";
echo "<td>" . ($row['id_agencia'] ?? 'NULL') . "</td>";
echo "<td>✅ SÍ</td>";
echo "</tr>";
}
echo "</table>";
echo "<p><strong>Templates que deberían aparecer en el formulario: $count_endpoint</strong></p>";
}
// 3. Probar el endpoint AJAX directamente
echo "<h3>3. Prueba del endpoint AJAX:</h3>";
echo "<p><a href='/IMPORTADORES/templates_rapidos/ajax_obtener_templates' target='_blank' style='background: #007bff; color: white; padding: 10px 15px; text-decoration: none; border-radius: 5px;'>🔗 Abrir endpoint AJAX en nueva pestaña</a></p>";
// 4. Verificar la sesión
echo "<h3>4. Estado de la sesión:</h3>";
echo "<pre>";
echo "SESSION:\n";
foreach ($_SESSION as $key => $value) {
if (is_string($value) || is_numeric($value)) {
echo " $key: $value\n";
}
}
echo "</pre>";
} catch (Exception $e) {
echo "<div style='color: red;'>❌ <strong>Error:</strong> " . $e->getMessage() . "</div>";
}
?>
<script>
// Script para probar el AJAX desde aquí mismo
function probarAjax() {
console.log('🔄 Probando AJAX...');
fetch('/IMPORTADORES/templates_rapidos/ajax_obtener_templates', {
method: 'GET',
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => {
console.log('📦 Status:', response.status);
return response.text();
})
.then(data => {
console.log('📄 Respuesta cruda:', data);
try {
const json = JSON.parse(data);
console.log('✅ JSON parseado:', json);
document.getElementById('ajax-result').innerHTML = `
<h4>Resultado del AJAX:</h4>
<pre style="background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto;">${JSON.stringify(json, null, 2)}</pre>
`;
} catch (e) {
console.error('❌ Error parseando JSON:', e);
document.getElementById('ajax-result').innerHTML = `
<h4>Respuesta del servidor (no es JSON válido):</h4>
<pre style="background: #fff3cd; padding: 15px; border-radius: 5px; overflow-x: auto;">${data}</pre>
`;
}
})
.catch(error => {
console.error('❌ Error AJAX:', error);
document.getElementById('ajax-result').innerHTML = `
<h4>Error en la petición:</h4>
<pre style="background: #f8d7da; padding: 15px; border-radius: 5px;">${error.message}</pre>
`;
});
}
</script>
<h3>5. Prueba AJAX en tiempo real:</h3>
<button onclick="probarAjax()" style="background: #28a745; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
🧪 Probar AJAX ahora
</button>
<div id="ajax-result" style="margin-top: 15px;"></div>
<hr>
<p><small><strong>💡 Instrucciones:</strong><br>
1. Revisa los templates en la tabla de arriba<br>
2. Verifica que tu usuario_id y agencia_id sean correctos<br>
3. Haz clic en "Probar AJAX ahora" para ver la respuesta en tiempo real<br>
4. Abre la consola del navegador (F12) para ver logs detallados</small></p>