feat: login unificado BI-CCC com deteccao automatica de role

- Adiciona coluna 'role' na tabela agentes (agente|admin)
- Migra admins existentes para tabela agentes com role='admin'
- Unifica login em /login com redirect baseado em role
- Sessao unificada req.session.user com {id, email, nome, role, agente_id}
- Middleware requireRole() para proteger rotas por role
- Admin panel com selector de role ao criar/editar usuarios
- Atualiza branding para "BI - CCC" com logo CambioReal
- Redirects: /admin/login -> /login, /admin/logout -> /logout

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-08 13:03:52 -05:00
parent 39900c3fe8
commit be2b090ddc
9 changed files with 2710 additions and 96 deletions

536
src/admin-panel.js Normal file
View File

@@ -0,0 +1,536 @@
/**
* Admin Panel - HTML builder for agent management
*/
function buildAdminHTML(agentes, admin) {
const now = new Date().toLocaleString('pt-BR');
return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BI - CCC - CambioReal Central Command</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--primary: #6C3FA0;
--primary-light: #8B5FBF;
--primary-dark: #4A2570;
--primary-bg: #F3EEFA;
--bg: #F0F2F5;
--card: #FFFFFF;
--text: #1A1D23;
--text-secondary: #5F6368;
--text-muted: #9AA0A6;
--border: #E8EAED;
--green: #1E8E3E;
--green-bg: #E6F4EA;
--blue: #1A73E8;
--blue-bg: #E8F0FE;
--orange: #E8710A;
--orange-bg: #FEF3E8;
--red: #D93025;
--red-bg: #FDE7E7;
--admin-accent: #2E7D32;
--admin-bg: #E8F5E9;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: var(--bg); color: var(--text); line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
.header {
background: linear-gradient(135deg, var(--admin-accent) 0%, #1B5E20 100%);
color: white; padding: 24px 40px;
display: flex; justify-content: space-between; align-items: center;
box-shadow: 0 2px 8px rgba(27,94,32,0.3);
}
.header h1 { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; }
.header .subtitle { font-size: 13px; opacity: 0.8; margin-top: 4px; font-weight: 400; }
.header-right { display: flex; align-items: center; gap: 16px; }
.header .badge {
background: rgba(255,255,255,0.15); backdrop-filter: blur(10px);
padding: 8px 16px; border-radius: 24px; font-size: 12px; font-weight: 600;
border: 1px solid rgba(255,255,255,0.2);
}
.btn-logout {
background: rgba(255,255,255,0.15); color: white; border: 1px solid rgba(255,255,255,0.3);
padding: 8px 16px; border-radius: 8px; font-size: 12px; font-weight: 600;
cursor: pointer; text-decoration: none; font-family: inherit; transition: all 0.15s;
}
.btn-logout:hover { background: rgba(255,255,255,0.25); }
.container { padding: 28px 40px; max-width: 1200px; margin: 0 auto; }
.toolbar {
display: flex; justify-content: space-between; align-items: center;
margin-bottom: 20px;
}
.toolbar h2 { font-size: 18px; font-weight: 700; color: var(--text); }
.btn-create {
background: var(--admin-accent); color: white; border: none;
padding: 10px 20px; border-radius: 8px; font-size: 13px; font-weight: 600;
font-family: inherit; cursor: pointer; transition: all 0.15s;
box-shadow: 0 2px 6px rgba(46,125,50,0.3);
}
.btn-create:hover { background: #25732a; transform: translateY(-1px); }
.table-card {
background: var(--card); border-radius: 12px; border: 1px solid var(--border);
box-shadow: 0 1px 3px rgba(0,0,0,0.06); overflow: hidden;
}
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
thead th {
background: #FAFBFC; padding: 12px 16px; text-align: left;
font-weight: 600; color: var(--text-secondary); font-size: 11px;
text-transform: uppercase; letter-spacing: 0.4px;
border-bottom: 2px solid var(--border); white-space: nowrap;
}
tbody td {
padding: 12px 16px; border-bottom: 1px solid #F3F4F6;
white-space: nowrap; vertical-align: middle;
}
tbody tr:hover { background: #F8F9FA; }
tbody tr:nth-child(even) { background: #FAFBFC; }
tbody tr:nth-child(even):hover { background: #F8F9FA; }
.status-badge {
display: inline-block; padding: 4px 10px; border-radius: 12px;
font-size: 11px; font-weight: 600; text-transform: uppercase;
}
.status-badge.active { background: var(--green-bg); color: var(--green); }
.status-badge.inactive { background: var(--red-bg); color: var(--red); }
.status-badge.admin { background: var(--admin-bg); color: var(--admin-accent); }
.status-badge.agent { background: var(--blue-bg); color: var(--blue); }
.actions { display: flex; gap: 6px; }
.btn-action {
padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600;
font-family: inherit; cursor: pointer; transition: all 0.15s; border: none;
}
.btn-emular { background: var(--green-bg); color: var(--green); text-decoration: none; }
.btn-emular:hover { background: #C8E6C9; }
.btn-edit { background: var(--blue-bg); color: var(--blue); }
.btn-edit:hover { background: #D2E3FC; }
.btn-toggle { background: var(--orange-bg); color: var(--orange); }
.btn-toggle:hover { background: #FDE7D8; }
.btn-password { background: var(--primary-bg); color: var(--primary); }
.btn-password:hover { background: #E8DCFA; }
.btn-delete { background: var(--red-bg); color: var(--red); }
.btn-delete:hover { background: #FBD5D5; }
/* Modal */
.modal-overlay {
display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.5); z-index: 1000;
align-items: center; justify-content: center;
}
.modal-overlay.active { display: flex; }
.modal {
background: var(--card); border-radius: 16px; width: 100%; max-width: 480px;
max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}
.modal-header {
padding: 20px 24px; border-bottom: 1px solid var(--border);
display: flex; justify-content: space-between; align-items: center;
}
.modal-header h3 { font-size: 16px; font-weight: 700; color: var(--text); }
.modal-close {
background: none; border: none; font-size: 24px; color: var(--text-muted);
cursor: pointer; line-height: 1;
}
.modal-close:hover { color: var(--text); }
.modal-body { padding: 24px; }
.form-group { margin-bottom: 18px; }
.form-group label {
display: block; font-size: 12px; font-weight: 600;
color: var(--text-secondary); text-transform: uppercase;
letter-spacing: 0.3px; margin-bottom: 6px;
}
.form-group input {
width: 100%; padding: 10px 14px; border: 1.5px solid var(--border);
border-radius: 8px; font-size: 14px; font-family: inherit;
color: var(--text); transition: all 0.15s; background: white;
}
.form-group input:focus {
outline: none; border-color: var(--admin-accent);
box-shadow: 0 0 0 3px rgba(46,125,50,0.12);
}
.form-group input:disabled {
background: #F5F5F5; color: var(--text-muted);
}
.form-group select {
width: 100%; padding: 10px 14px; border: 1.5px solid var(--border);
border-radius: 8px; font-size: 14px; font-family: inherit;
color: var(--text); transition: all 0.15s; background: white;
cursor: pointer;
}
.form-group select:focus {
outline: none; border-color: var(--admin-accent);
box-shadow: 0 0 0 3px rgba(46,125,50,0.12);
}
.modal-footer {
padding: 16px 24px; border-top: 1px solid var(--border);
display: flex; justify-content: flex-end; gap: 10px;
}
.btn-cancel {
padding: 10px 20px; border-radius: 8px; font-size: 13px; font-weight: 600;
font-family: inherit; cursor: pointer; transition: all 0.15s;
background: white; border: 1.5px solid var(--border); color: var(--text);
}
.btn-cancel:hover { background: #F5F5F5; }
.btn-submit {
padding: 10px 20px; border-radius: 8px; font-size: 13px; font-weight: 600;
font-family: inherit; cursor: pointer; transition: all 0.15s;
background: var(--admin-accent); border: none; color: white;
box-shadow: 0 2px 6px rgba(46,125,50,0.3);
}
.btn-submit:hover { background: #25732a; }
.alert {
padding: 12px 16px; border-radius: 8px; font-size: 13px; font-weight: 500;
margin-bottom: 20px; display: none;
}
.alert.success { background: var(--green-bg); color: var(--green); }
.alert.error { background: var(--red-bg); color: var(--red); }
.alert.show { display: block; }
.footer { text-align: center; padding: 20px; font-size: 12px; color: var(--text-muted); }
@media (max-width: 768px) {
.container { padding: 20px; }
.header { padding: 20px; flex-direction: column; gap: 12px; }
.header-right { width: 100%; justify-content: space-between; }
.toolbar { flex-direction: column; gap: 12px; align-items: flex-start; }
}
</style>
</head>
<body>
<div class="header">
<div>
<h1>BI - CCC</h1>
<div class="subtitle">CambioReal Central Command</div>
</div>
<div class="header-right">
<div class="badge">Admin: ${admin.nome}</div>
<a href="/admin/dashboard" class="btn-logout" style="background:#1A73E8;margin-right:8px;">Dashboard Geral</a>
<a href="/logout" class="btn-logout">Sair</a>
</div>
</div>
<div class="container">
<div id="alertBox" class="alert"></div>
<div class="toolbar">
<h2>Usuarios Cadastrados (${agentes.length})</h2>
<button class="btn-create" onclick="openCreateModal()">+ Novo Usuario</button>
</div>
<div class="table-card">
<div class="table-wrap">
<table>
<thead>
<tr>
<th>ID</th>
<th>Nome</th>
<th>E-mail</th>
<th>Role</th>
<th>Agente ID</th>
<th>Status</th>
<th>Criado em</th>
<th>Acoes</th>
</tr>
</thead>
<tbody id="agentesTable">
${agentes.map(a => `
<tr data-id="${a.id}">
<td>${a.id}</td>
<td>${a.nome}</td>
<td>${a.email}</td>
<td><span class="status-badge ${a.role === 'admin' ? 'admin' : 'agent'}">${a.role === 'admin' ? 'Admin' : 'Agente'}</span></td>
<td>${a.role === 'admin' ? '-' : a.agente_id}</td>
<td><span class="status-badge ${a.ativo ? 'active' : 'inactive'}">${a.ativo ? 'Ativo' : 'Inativo'}</span></td>
<td>${a.created_at ? new Date(a.created_at).toLocaleDateString('pt-BR') : '-'}</td>
<td class="actions">
${a.role === 'agente' ? `<a href="/admin/emular/${a.agente_id}" class="btn-action btn-emular" title="Ver como este agente">Emular</a>` : ''}
<button class="btn-action btn-edit" onclick="openEditModal(${a.id}, '${a.nome.replace(/'/g, "\\'")}', '${a.email.replace(/'/g, "\\'")}', ${a.agente_id}, '${a.role || 'agente'}', event)">Editar</button>
<button class="btn-action btn-toggle" onclick="toggleAgente(${a.id}, ${a.ativo})">${a.ativo ? 'Desativar' : 'Ativar'}</button>
<button class="btn-action btn-password" onclick="openPasswordModal(${a.id}, '${a.nome.replace(/'/g, "\\'")}')">Senha</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
</div>
</div>
<div class="footer">BI - CCC - CambioReal Central Command - ${now}</div>
<!-- Create/Edit Modal -->
<div class="modal-overlay" id="agentModal">
<div class="modal">
<div class="modal-header">
<h3 id="modalTitle">Novo Agente</h3>
<button class="modal-close" onclick="closeModal('agentModal')">&times;</button>
</div>
<form id="agentForm" onsubmit="submitAgentForm(event)">
<div class="modal-body">
<input type="hidden" id="agentId" name="id">
<div class="form-group">
<label>Nome</label>
<input type="text" id="agentNome" name="nome" required placeholder="Nome do usuario">
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="agentEmail" name="email" required placeholder="usuario@email.com">
</div>
<div class="form-group">
<label>Tipo de Usuario</label>
<select id="agentRole" name="role" onchange="toggleAgenteIdField()">
<option value="agente">Agente</option>
<option value="admin">Administrador</option>
</select>
</div>
<div class="form-group" id="agenteIdGroup">
<label>Agente ID (Sistema)</label>
<input type="number" id="agentAgenteId" name="agente_id" placeholder="ID numerico do agente">
</div>
<div class="form-group" id="senhaGroup">
<label>Senha</label>
<input type="password" id="agentSenha" name="senha" placeholder="Senha de acesso" minlength="6">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-cancel" onclick="closeModal('agentModal')">Cancelar</button>
<button type="submit" class="btn-submit" id="submitBtn">Criar Agente</button>
</div>
</form>
</div>
</div>
<!-- Password Reset Modal -->
<div class="modal-overlay" id="passwordModal">
<div class="modal">
<div class="modal-header">
<h3 id="passwordModalTitle">Redefinir Senha</h3>
<button class="modal-close" onclick="closeModal('passwordModal')">&times;</button>
</div>
<form id="passwordForm" onsubmit="submitPasswordForm(event)">
<div class="modal-body">
<input type="hidden" id="passwordAgentId">
<div class="form-group">
<label>Nova Senha</label>
<input type="password" id="newPassword" required placeholder="Nova senha" minlength="6">
</div>
<div class="form-group">
<label>Confirmar Senha</label>
<input type="password" id="confirmPassword" required placeholder="Confirme a senha" minlength="6">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-cancel" onclick="closeModal('passwordModal')">Cancelar</button>
<button type="submit" class="btn-submit">Redefinir Senha</button>
</div>
</form>
</div>
</div>
<script>
let isEditing = false;
function showAlert(message, type) {
const alert = document.getElementById('alertBox');
alert.textContent = message;
alert.className = 'alert ' + type + ' show';
setTimeout(() => { alert.className = 'alert'; }, 4000);
}
function toggleAgenteIdField() {
const role = document.getElementById('agentRole').value;
const agenteIdGroup = document.getElementById('agenteIdGroup');
const agenteIdInput = document.getElementById('agentAgenteId');
if (role === 'admin') {
agenteIdGroup.style.display = 'none';
agenteIdInput.required = false;
agenteIdInput.value = '';
} else {
agenteIdGroup.style.display = 'block';
agenteIdInput.required = !isEditing;
}
}
function openCreateModal(event) {
if (event) event.stopPropagation();
isEditing = false;
document.getElementById('modalTitle').textContent = 'Novo Usuario';
document.getElementById('submitBtn').textContent = 'Criar Usuario';
document.getElementById('agentForm').reset();
document.getElementById('agentId').value = '';
document.getElementById('agentRole').value = 'agente';
document.getElementById('senhaGroup').style.display = 'block';
document.getElementById('agentSenha').required = true;
toggleAgenteIdField();
setTimeout(() => {
document.getElementById('agentModal').classList.add('active');
document.getElementById('agentNome').focus();
}, 10);
}
function openEditModal(id, nome, email, agenteId, role, event) {
if (event) event.stopPropagation();
isEditing = true;
document.getElementById('modalTitle').textContent = 'Editar Usuario';
document.getElementById('submitBtn').textContent = 'Salvar Alteracoes';
document.getElementById('agentId').value = id;
document.getElementById('agentNome').value = nome;
document.getElementById('agentEmail').value = email;
document.getElementById('agentAgenteId').value = agenteId;
document.getElementById('agentRole').value = role || 'agente';
document.getElementById('senhaGroup').style.display = 'none';
document.getElementById('agentSenha').required = false;
toggleAgenteIdField();
setTimeout(() => {
document.getElementById('agentModal').classList.add('active');
document.getElementById('agentNome').focus();
}, 10);
}
function openPasswordModal(id, nome) {
document.getElementById('passwordModalTitle').textContent = 'Redefinir Senha: ' + nome;
document.getElementById('passwordAgentId').value = id;
document.getElementById('passwordForm').reset();
document.getElementById('passwordModal').classList.add('active');
document.getElementById('newPassword').focus();
}
function closeModal(id) {
document.getElementById(id).classList.remove('active');
}
async function submitAgentForm(e) {
e.preventDefault();
const id = document.getElementById('agentId').value;
const role = document.getElementById('agentRole').value;
const data = {
nome: document.getElementById('agentNome').value,
email: document.getElementById('agentEmail').value,
role: role,
};
if (role === 'agente') {
const agenteId = document.getElementById('agentAgenteId').value;
if (!isEditing && !agenteId) {
showAlert('Agente ID e obrigatorio para agentes', 'error');
return;
}
data.agente_id = parseInt(agenteId) || 0;
}
if (!isEditing) {
data.senha = document.getElementById('agentSenha').value;
}
try {
const url = isEditing ? '/admin/agentes/' + id : '/admin/agentes';
const method = isEditing ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
if (res.ok) {
showAlert(isEditing ? 'Usuario atualizado com sucesso!' : 'Usuario criado com sucesso!', 'success');
closeModal('agentModal');
setTimeout(() => location.reload(), 1000);
} else {
showAlert(result.error || 'Erro ao salvar usuario', 'error');
}
} catch (err) {
showAlert('Erro de conexao', 'error');
}
}
async function submitPasswordForm(e) {
e.preventDefault();
const id = document.getElementById('passwordAgentId').value;
const newPassword = document.getElementById('newPassword').value;
const confirmPassword = document.getElementById('confirmPassword').value;
if (newPassword !== confirmPassword) {
showAlert('As senhas nao coincidem', 'error');
return;
}
try {
const res = await fetch('/admin/agentes/' + id, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ senha: newPassword })
});
const result = await res.json();
if (res.ok) {
showAlert('Senha redefinida com sucesso!', 'success');
closeModal('passwordModal');
} else {
showAlert(result.error || 'Erro ao redefinir senha', 'error');
}
} catch (err) {
showAlert('Erro de conexao', 'error');
}
}
async function toggleAgente(id, currentStatus) {
const action = currentStatus ? 'desativar' : 'ativar';
if (!confirm('Deseja ' + action + ' este agente?')) return;
try {
const res = await fetch('/admin/agentes/' + id, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ativo: currentStatus ? 0 : 1 })
});
const result = await res.json();
if (res.ok) {
showAlert('Agente ' + (currentStatus ? 'desativado' : 'ativado') + ' com sucesso!', 'success');
setTimeout(() => location.reload(), 1000);
} else {
showAlert(result.error || 'Erro ao alterar status', 'error');
}
} catch (err) {
showAlert('Erro de conexao', 'error');
}
}
// Close modal on overlay click (not on modal content)
document.querySelectorAll('.modal-overlay').forEach(overlay => {
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
overlay.classList.remove('active');
}
});
});
// Prevent clicks inside modal from closing it
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => {
e.stopPropagation();
});
});
// Close modal on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
document.querySelectorAll('.modal-overlay.active').forEach(m => m.classList.remove('active'));
}
});
</script>
</body>
</html>`;
}
module.exports = { buildAdminHTML };