feat(pos): chatbot IA con OpenRouter — busqueda de partes por lenguaje natural
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
244
pos/static/js/chat.js
Normal file
244
pos/static/js/chat.js
Normal file
@@ -0,0 +1,244 @@
|
||||
// /home/Autopartes/pos/static/js/chat.js
|
||||
// AI Chat Widget for Nexus POS — natural language parts lookup
|
||||
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// ─── State ───
|
||||
let isOpen = false;
|
||||
let isSending = false;
|
||||
const history = []; // conversation history for AI context
|
||||
|
||||
// ─── Build DOM ───
|
||||
function init() {
|
||||
// FAB button
|
||||
const fab = document.createElement('button');
|
||||
fab.className = 'chat-fab';
|
||||
fab.id = 'chatFab';
|
||||
fab.title = 'Asistente IA';
|
||||
fab.innerHTML = '💬'; // speech bubble emoji
|
||||
fab.setAttribute('aria-label', 'Abrir asistente IA');
|
||||
|
||||
// Chat panel
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'chat-panel';
|
||||
panel.id = 'chatPanel';
|
||||
panel.innerHTML = `
|
||||
<div class="chat-header">
|
||||
<h3>Asistente IA — Buscar partes</h3>
|
||||
<button class="chat-header-close" id="chatClose" aria-label="Cerrar">×</button>
|
||||
</div>
|
||||
<div class="chat-messages" id="chatMessages">
|
||||
<div class="chat-msg ai">Hola, soy el asistente de Nexus. Dime que refaccion necesitas y te ayudo a encontrarla.</div>
|
||||
<div class="chat-typing" id="chatTyping">
|
||||
<span></span><span></span><span></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-input-area">
|
||||
<textarea class="chat-input" id="chatInput" placeholder="Ej: Balatas para Tsuru 2015..." rows="1"></textarea>
|
||||
<button class="chat-send-btn" id="chatSend" aria-label="Enviar">▶</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(fab);
|
||||
document.body.appendChild(panel);
|
||||
|
||||
// Events
|
||||
fab.addEventListener('click', toggleChat);
|
||||
document.getElementById('chatClose').addEventListener('click', toggleChat);
|
||||
document.getElementById('chatSend').addEventListener('click', sendMessage);
|
||||
document.getElementById('chatInput').addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-resize textarea
|
||||
document.getElementById('chatInput').addEventListener('input', function () {
|
||||
this.style.height = 'auto';
|
||||
this.style.height = Math.min(this.scrollHeight, 80) + 'px';
|
||||
});
|
||||
}
|
||||
|
||||
function toggleChat() {
|
||||
isOpen = !isOpen;
|
||||
const panel = document.getElementById('chatPanel');
|
||||
const fab = document.getElementById('chatFab');
|
||||
if (isOpen) {
|
||||
panel.classList.add('open');
|
||||
fab.style.display = 'none';
|
||||
document.getElementById('chatInput').focus();
|
||||
} else {
|
||||
panel.classList.remove('open');
|
||||
fab.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
|
||||
function getToken() {
|
||||
// app-init.js stores token in window.__pos or localStorage
|
||||
if (window.__pos && window.__pos.token) return window.__pos.token;
|
||||
return localStorage.getItem('pos_token') || '';
|
||||
}
|
||||
|
||||
// ─── Send message ───
|
||||
async function sendMessage() {
|
||||
if (isSending) return;
|
||||
const input = document.getElementById('chatInput');
|
||||
const text = input.value.trim();
|
||||
if (!text) return;
|
||||
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
|
||||
// Add user bubble
|
||||
addBubble(text, 'user');
|
||||
|
||||
// Keep history for context (last 10 exchanges)
|
||||
history.push({ role: 'user', content: text });
|
||||
if (history.length > 20) history.splice(0, 2);
|
||||
|
||||
// Show typing
|
||||
isSending = true;
|
||||
document.getElementById('chatSend').disabled = true;
|
||||
showTyping(true);
|
||||
|
||||
try {
|
||||
const token = getToken();
|
||||
const resp = await fetch('/pos/api/chat', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + token
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: text,
|
||||
history: history.slice(-10)
|
||||
})
|
||||
});
|
||||
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) {
|
||||
addBubble('Error: ' + (data.error || resp.statusText), 'ai');
|
||||
return;
|
||||
}
|
||||
|
||||
// AI response bubble
|
||||
const aiMsg = data.response || 'Sin respuesta.';
|
||||
addBubble(aiMsg, 'ai');
|
||||
history.push({ role: 'assistant', content: aiMsg });
|
||||
|
||||
// Vehicle info
|
||||
if (data.vehicle && data.vehicle.brand_id) {
|
||||
addVehicleBanner(data.vehicle);
|
||||
}
|
||||
|
||||
// Search results
|
||||
if (data.search_results && data.search_results.length > 0) {
|
||||
addPartResults(data.search_results);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
addBubble('Error de conexion: ' + err.message, 'ai');
|
||||
} finally {
|
||||
isSending = false;
|
||||
document.getElementById('chatSend').disabled = false;
|
||||
showTyping(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── DOM helpers ───
|
||||
function addBubble(text, role) {
|
||||
const container = document.getElementById('chatMessages');
|
||||
const typing = document.getElementById('chatTyping');
|
||||
const div = document.createElement('div');
|
||||
div.className = 'chat-msg ' + role;
|
||||
div.textContent = text;
|
||||
container.insertBefore(div, typing);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function addVehicleBanner(vehicle) {
|
||||
const container = document.getElementById('chatMessages');
|
||||
const typing = document.getElementById('chatTyping');
|
||||
const div = document.createElement('div');
|
||||
div.className = 'chat-vehicle-banner';
|
||||
|
||||
let html = '<strong>' + esc(vehicle.brand || '') + ' ' + esc(vehicle.model || '') + '</strong>';
|
||||
if (vehicle.year) html += ' ' + vehicle.year;
|
||||
|
||||
if (vehicle.mye_options && vehicle.mye_options.length > 0) {
|
||||
html += '<br>Motorizaciones encontradas:';
|
||||
vehicle.mye_options.forEach(function (opt) {
|
||||
html += '<br>• ' + esc(opt.engine);
|
||||
if (opt.trim) html += ' (' + esc(opt.trim) + ')';
|
||||
});
|
||||
}
|
||||
|
||||
div.innerHTML = html;
|
||||
container.insertBefore(div, typing);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function addPartResults(parts) {
|
||||
const container = document.getElementById('chatMessages');
|
||||
const typing = document.getElementById('chatTyping');
|
||||
|
||||
const wrapper = document.createElement('div');
|
||||
wrapper.className = 'chat-parts';
|
||||
|
||||
parts.slice(0, 8).forEach(function (p) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'chat-part-card';
|
||||
|
||||
const stockQty = p.local_stock || 0;
|
||||
const stockClass = stockQty > 0 ? 'in-stock' : '';
|
||||
const stockText = stockQty > 0 ? (stockQty + ' en stock') : 'Sin stock local';
|
||||
const name = p.name_es || p.name_part || '';
|
||||
const partNum = p.oem_part_number || '';
|
||||
const priceText = p.price_1 ? ('$' + parseFloat(p.price_1).toFixed(2)) : '';
|
||||
|
||||
card.innerHTML =
|
||||
'<div class="part-number">' + esc(partNum) + (priceText ? ' — ' + priceText : '') + '</div>' +
|
||||
'<div class="part-name">' + esc(name) + '</div>' +
|
||||
'<div class="part-stock ' + stockClass + '">' + esc(stockText) + '</div>';
|
||||
|
||||
// Click to open detail (if catalog page has a detail function)
|
||||
card.addEventListener('click', function () {
|
||||
if (p.id_part && typeof window.openPartDetail === 'function') {
|
||||
window.openPartDetail(p.id_part);
|
||||
toggleChat();
|
||||
}
|
||||
});
|
||||
|
||||
wrapper.appendChild(card);
|
||||
});
|
||||
|
||||
container.insertBefore(wrapper, typing);
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
function showTyping(show) {
|
||||
const el = document.getElementById('chatTyping');
|
||||
if (el) el.classList.toggle('visible', show);
|
||||
if (show) scrollToBottom();
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
const el = document.getElementById('chatMessages');
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
function esc(s) {
|
||||
const d = document.createElement('div');
|
||||
d.textContent = s;
|
||||
return d.innerHTML;
|
||||
}
|
||||
|
||||
// ─── Init when DOM ready ───
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user