Files
crm.clientright.ru/test_context_data.html

288 lines
12 KiB
HTML
Raw Normal View History

<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🔍 Тест данных контекста</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background: #f5f5f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.data-display {
background: #2d3748;
color: #e2e8f0;
padding: 15px;
border-radius: 8px;
font-family: 'Courier New', monospace;
white-space: pre-wrap;
margin: 10px 0;
}
.test-button {
background: #667eea;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
margin: 10px 5px;
}
.test-button:hover {
background: #5a67d8;
}
.status {
padding: 10px;
border-radius: 5px;
margin: 10px 0;
}
.status.success {
background: #d4edda;
color: #155724;
}
.status.error {
background: #f8d7da;
color: #721c24;
}
</style>
</head>
<body>
<div class="container">
<h1>🔍 Тест данных контекста</h1>
<div class="status" id="status">Готов к тестированию</div>
<h2>📊 Текущие данные контекста:</h2>
<div id="context-data" class="data-display">Нажмите "Получить данные"</div>
<button class="test-button" onclick="getContextData()">📊 Получить данные</button>
<button class="test-button" onclick="testTypebotSend()">🚀 Тест отправки в Typebot</button>
<h2>🔧 Отладочная информация:</h2>
<div id="debug-info" class="data-display">Нажмите "Показать отладку"</div>
<button class="test-button" onclick="showDebugInfo()">🔍 Показать отладку</button>
<h2>📝 Логи:</h2>
<div id="logs" class="data-display">Логи будут отображаться здесь</div>
<button class="test-button" onclick="clearLogs()">🗑️ Очистить логи</button>
</div>
<script>
let logs = [];
function log(message) {
const timestamp = new Date().toLocaleTimeString();
logs.push(`[${timestamp}] ${message}`);
updateLogsDisplay();
}
function updateLogsDisplay() {
document.getElementById('logs').textContent = logs.join('\n');
}
function clearLogs() {
logs = [];
updateLogsDisplay();
}
// Функция для получения контекста CRM (улучшенная версия)
function getCurrentContext() {
const urlParams = new URLSearchParams(window.location.search);
const projectId = urlParams.get('record') || '';
// Получаем данные из URL
const currentModule = urlParams.get('module') || '';
const currentView = urlParams.get('view') || '';
// Получаем данные из глобальных переменных CRM
let userId = '';
let userName = '';
let userEmail = '';
// Пробуем разные способы получения данных пользователя
if (typeof _USERMETA !== 'undefined' && _USERMETA.id) {
userId = _USERMETA.id;
userName = _USERMETA.user_name || '';
userEmail = _USERMETA.email1 || '';
} else if (typeof window.userId !== 'undefined') {
userId = window.userId;
} else if (typeof window.current_user_id !== 'undefined') {
userId = window.current_user_id;
}
// Получаем данные модуля
let moduleName = currentModule;
if (typeof _META !== 'undefined' && _META.module) {
moduleName = _META.module;
} else if (typeof window.module !== 'undefined') {
moduleName = window.module;
}
// Получаем данные представления
let viewName = currentView;
if (typeof _META !== 'undefined' && _META.view) {
viewName = _META.view;
} else if (typeof window.view !== 'undefined') {
viewName = window.view;
}
// Получаем название проекта/компании
let projectName = '';
try {
const recordLabel = document.querySelector('.recordLabel, .record-name, h1');
if (recordLabel) {
projectName = recordLabel.textContent.trim();
}
} catch (e) {
console.log('AI Drawer: Could not get project name:', e);
}
// Получаем заголовок страницы
let pageTitle = document.title || '';
// Получаем текущую дату
const currentDate = new Date().toISOString();
const context = {
projectId: projectId,
module: moduleName,
view: viewName,
userId: userId,
userName: userName,
userEmail: userEmail,
projectName: projectName,
pageTitle: pageTitle,
currentDate: currentDate,
url: window.location.href,
timestamp: Date.now()
};
console.log('AI Drawer: Context data:', context);
return context;
}
function getContextData() {
log('🔄 Получение данных контекста...');
const context = getCurrentContext();
const contextDisplay = document.getElementById('context-data');
// Форматируем данные для отображения
const formattedData = JSON.stringify(context, null, 2);
contextDisplay.textContent = formattedData;
log('✅ Данные контекста получены:');
log(formattedData);
// Показываем статус
const statusDiv = document.getElementById('status');
statusDiv.className = 'status success';
statusDiv.textContent = '✅ Данные контекста получены успешно';
}
async function testTypebotSend() {
const context = getCurrentContext();
const message = 'Тестовое сообщение из CRM';
log(`📤 Отправка тестового сообщения в Typebot...`);
log(`📊 Контекст: ${JSON.stringify(context, null, 2)}`);
const statusDiv = document.getElementById('status');
statusDiv.className = 'status';
statusDiv.textContent = '⏳ Отправка в Typebot...';
try {
const response = await fetch('/aiassist/typebot_proxy.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'startChat',
message: message,
context: context
})
});
const result = await response.json();
log(`📥 Ответ от Typebot: ${JSON.stringify(result, null, 2)}`);
if (result.success) {
statusDiv.className = 'status success';
statusDiv.textContent = '✅ Сообщение отправлено успешно';
} else {
statusDiv.className = 'status error';
statusDiv.textContent = `❌ Ошибка: ${result.error || 'Неизвестная ошибка'}`;
}
} catch (error) {
log(`❌ Ошибка отправки: ${error.message}`);
statusDiv.className = 'status error';
statusDiv.textContent = `❌ Ошибка сети: ${error.message}`;
}
}
function showDebugInfo() {
log('🔍 Сбор отладочной информации...');
const debugInfo = {
// URL информация
url: window.location.href,
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash,
// Доступные глобальные переменные
globals: {
_META: typeof _META !== 'undefined' ? _META : 'Не определено',
_USERMETA: typeof _USERMETA !== 'undefined' ? _USERMETA : 'Не определено',
_MODULE: typeof _MODULE !== 'undefined' ? _MODULE : 'Не определено',
_VIEW: typeof _VIEW !== 'undefined' ? _VIEW : 'Не определено',
window_userId: typeof window.userId !== 'undefined' ? window.userId : 'Не определено',
window_module: typeof window.module !== 'undefined' ? window.module : 'Не определено',
window_view: typeof window.view !== 'undefined' ? window.view : 'Не определено'
},
// Параметры URL
urlParams: Object.fromEntries(new URLSearchParams(window.location.search)),
// Информация о странице
pageInfo: {
title: document.title,
referrer: document.referrer,
userAgent: navigator.userAgent
},
// Доступные элементы на странице
elements: {
recordLabel: document.querySelector('.recordLabel')?.textContent || 'Не найден',
recordName: document.querySelector('.record-name')?.textContent || 'Не найден',
h1: document.querySelector('h1')?.textContent || 'Не найден'
}
};
const debugDisplay = document.getElementById('debug-info');
debugDisplay.textContent = JSON.stringify(debugInfo, null, 2);
log('✅ Отладочная информация собрана');
}
// Автоматическое получение данных при загрузке
window.addEventListener('load', function() {
log('🚀 Страница тестирования загружена');
getContextData();
});
</script>
</body>
</html>