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:
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>BI Agentes — Login</title>
|
||||
<title>BI - CCC | CambioReal</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root {
|
||||
@@ -45,24 +45,31 @@
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.login-header .logo {
|
||||
width: 56px; height: 56px;
|
||||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
|
||||
border-radius: 14px;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 80px; height: 80px;
|
||||
margin: 0 auto 16px;
|
||||
font-size: 28px;
|
||||
color: white;
|
||||
}
|
||||
.login-header .logo img {
|
||||
width: 100%; height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
.login-header h1 {
|
||||
font-size: 22px;
|
||||
font-size: 24px;
|
||||
font-weight: 800;
|
||||
color: var(--text);
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
.login-header .subtitle {
|
||||
font-size: 12px;
|
||||
color: var(--primary);
|
||||
margin-top: 4px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
.login-header p {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
margin-top: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
@@ -134,15 +141,16 @@
|
||||
<div class="login-container">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="logo">↔</div>
|
||||
<h1>BI Agentes</h1>
|
||||
<p>CambioReal — Dashboard de Transacoes</p>
|
||||
<div class="logo"><img src="/public/logo-small.png" alt="CambioReal"></div>
|
||||
<h1>BI - CCC</h1>
|
||||
<div class="subtitle">Central Command Center</div>
|
||||
<p>Acesso unificado para agentes e admins</p>
|
||||
</div>
|
||||
<div class="error-msg" id="errorMsg"></div>
|
||||
<form id="loginForm" method="POST" action="/login">
|
||||
<div class="form-group">
|
||||
<label>E-mail</label>
|
||||
<input type="email" name="email" id="email" required placeholder="agente@email.com" autocomplete="email">
|
||||
<input type="email" name="email" id="email" required placeholder="seu@email.com" autocomplete="email">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>Senha</label>
|
||||
|
||||
BIN
public/logo-small.png
Normal file
BIN
public/logo-small.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.8 KiB |
240
server.js
240
server.js
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* BI Agentes — CambioReal
|
||||
* BI - CCC (Central Command Center) — CambioReal
|
||||
* Login Unificado: todos os usuarios acessam via /login
|
||||
*
|
||||
* Uso: node server.js
|
||||
* Abre: http://localhost:3080
|
||||
@@ -9,12 +10,13 @@ require('dotenv').config();
|
||||
const express = require('express');
|
||||
const session = require('express-session');
|
||||
const path = require('path');
|
||||
const { authenticate, requireAuth } = require('./src/auth');
|
||||
const { fetchTransacoes, serialize } = require('./src/queries');
|
||||
const { authenticate, requireAuth, requireRole, createAgente, createUser } = require('./src/auth');
|
||||
const { fetchTransacoes, fetchAllTransacoes, serialize, fetchDailyStats } = require('./src/queries');
|
||||
const { buildHTML } = require('./src/dashboard');
|
||||
|
||||
// Initialize SQLite (creates tables on first run)
|
||||
require('./src/db-local');
|
||||
const { buildAdminHTML } = require('./src/admin-panel');
|
||||
const { buildAdminHomeHTML } = require('./src/admin-home');
|
||||
const bcrypt = require('bcrypt');
|
||||
const db = require('./src/db-local');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3080;
|
||||
@@ -32,45 +34,76 @@ app.use(session({
|
||||
// Static files
|
||||
app.use('/public', express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// --- Routes ---
|
||||
// --- Unified Login Routes ---
|
||||
|
||||
// Root -> login page (or redirect if logged in)
|
||||
app.get('/', (req, res) => {
|
||||
if (req.session?.user) {
|
||||
return res.redirect(req.session.user.role === 'admin' ? '/admin' : '/dashboard');
|
||||
}
|
||||
res.redirect('/login');
|
||||
});
|
||||
|
||||
// Login page
|
||||
app.get('/login', (req, res) => {
|
||||
if (req.session && req.session.agente) return res.redirect('/dashboard');
|
||||
if (req.session?.user) {
|
||||
return res.redirect(req.session.user.role === 'admin' ? '/admin' : '/dashboard');
|
||||
}
|
||||
res.sendFile(path.join(__dirname, 'public', 'login.html'));
|
||||
});
|
||||
|
||||
// Login POST
|
||||
// Unified Login POST - detects role and redirects accordingly
|
||||
app.post('/login', async (req, res) => {
|
||||
const { email, senha } = req.body;
|
||||
try {
|
||||
const agente = await authenticate(email, senha);
|
||||
if (!agente) return res.redirect('/login?error=1');
|
||||
req.session.agente = {
|
||||
id: agente.id,
|
||||
email: agente.email,
|
||||
agente_id: agente.agente_id,
|
||||
nome: agente.nome,
|
||||
const user = await authenticate(email, senha);
|
||||
if (!user) return res.redirect('/login?error=1');
|
||||
|
||||
// Unified session
|
||||
req.session.user = {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
nome: user.nome,
|
||||
role: user.role || 'agente',
|
||||
agente_id: user.agente_id
|
||||
};
|
||||
res.redirect('/dashboard');
|
||||
|
||||
// Redirect based on role
|
||||
if (user.role === 'admin') {
|
||||
res.redirect('/admin');
|
||||
} else {
|
||||
res.redirect('/dashboard');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login error:', err);
|
||||
res.redirect('/login?error=1');
|
||||
}
|
||||
});
|
||||
|
||||
// Logout
|
||||
// Unified Logout
|
||||
app.get('/logout', (req, res) => {
|
||||
req.session.destroy(() => res.redirect('/login'));
|
||||
});
|
||||
|
||||
// Dashboard (protected)
|
||||
app.get('/dashboard', requireAuth, async (req, res) => {
|
||||
// Legacy admin login - redirect to unified login
|
||||
app.get('/admin/login', (req, res) => {
|
||||
res.redirect('/login');
|
||||
});
|
||||
|
||||
// Legacy admin logout - redirect to unified logout
|
||||
app.get('/admin/logout', (req, res) => {
|
||||
res.redirect('/logout');
|
||||
});
|
||||
|
||||
// --- Agent Routes ---
|
||||
|
||||
// Dashboard (agente only)
|
||||
app.get('/dashboard', requireRole('agente'), async (req, res) => {
|
||||
try {
|
||||
const agente = req.session.agente;
|
||||
const { rowsBrlUsd, rowsUsdBrl } = await fetchTransacoes(agente.agente_id);
|
||||
const user = req.session.user;
|
||||
const { rowsBrlUsd, rowsUsdBrl } = await fetchTransacoes(user.agente_id);
|
||||
const data = serialize(rowsBrlUsd, rowsUsdBrl);
|
||||
const html = buildHTML(data, agente);
|
||||
const html = buildHTML(data, user);
|
||||
res.send(html);
|
||||
} catch (err) {
|
||||
console.error('Dashboard error:', err);
|
||||
@@ -78,10 +111,165 @@ app.get('/dashboard', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Root redirect
|
||||
app.get('/', (req, res) => res.redirect('/dashboard'));
|
||||
// --- Admin Routes ---
|
||||
|
||||
// Admin home (admin only) - Fast daily overview
|
||||
app.get('/admin', requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const stats = await fetchDailyStats();
|
||||
const html = buildAdminHomeHTML(stats, req.session.user);
|
||||
res.send(html);
|
||||
} catch (err) {
|
||||
console.error('Admin home error:', err);
|
||||
res.status(500).send('Erro ao carregar home admin: ' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Admin agents management (admin only)
|
||||
app.get('/admin/agentes', requireRole('admin'), (req, res) => {
|
||||
try {
|
||||
const agentes = db.prepare('SELECT * FROM agentes ORDER BY id DESC').all();
|
||||
const html = buildAdminHTML(agentes, req.session.user);
|
||||
res.send(html);
|
||||
} catch (err) {
|
||||
console.error('Admin panel error:', err);
|
||||
res.status(500).send('Erro ao carregar painel admin: ' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Admin Dashboard - view ALL clients data (admin only)
|
||||
app.get('/admin/dashboard', requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const user = req.session.user;
|
||||
const dias = parseInt(req.query.dias) || 90;
|
||||
const html = buildHTML([], { nome: `Admin - Ultimos ${dias} dias`, email: user.email }, false, dias, true);
|
||||
res.send(html);
|
||||
} catch (err) {
|
||||
console.error('Admin dashboard error:', err);
|
||||
res.status(500).send('Erro ao carregar dashboard admin: ' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
// API endpoint for admin dashboard data (admin only)
|
||||
app.get('/admin/api/data', requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const dias = parseInt(req.query.dias) || 90;
|
||||
const { rowsBrlUsd, rowsUsdBrl } = await fetchAllTransacoes(dias);
|
||||
const data = serialize(rowsBrlUsd, rowsUsdBrl);
|
||||
res.json({ success: true, data, count: data.length });
|
||||
} catch (err) {
|
||||
console.error('Admin API error:', err);
|
||||
res.status(500).json({ success: false, error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Admin emulate agent - view dashboard as specific agent (admin only)
|
||||
app.get('/admin/emular/:agente_id', requireRole('admin'), async (req, res) => {
|
||||
try {
|
||||
const agenteId = parseInt(req.params.agente_id);
|
||||
const agente = db.prepare('SELECT * FROM agentes WHERE agente_id = ?').get(agenteId);
|
||||
|
||||
if (!agente) {
|
||||
return res.status(404).send('Agente nao encontrado');
|
||||
}
|
||||
|
||||
const { rowsBrlUsd, rowsUsdBrl } = await fetchTransacoes(agenteId);
|
||||
const data = serialize(rowsBrlUsd, rowsUsdBrl);
|
||||
const html = buildHTML(data, {
|
||||
nome: agente.nome + ' (Emulando)',
|
||||
agente_id: agenteId,
|
||||
email: agente.email
|
||||
}, true, null, false, true); // isEmulating = true
|
||||
res.send(html);
|
||||
} catch (err) {
|
||||
console.error('Admin emulate error:', err);
|
||||
res.status(500).send('Erro ao emular agente: ' + err.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Create user (admin only)
|
||||
app.post('/admin/agentes', requireRole('admin'), async (req, res) => {
|
||||
const { nome, email, agente_id, senha, role } = req.body;
|
||||
try {
|
||||
if (!nome || !email || !senha) {
|
||||
return res.status(400).json({ error: 'Nome, email e senha sao obrigatorios' });
|
||||
}
|
||||
|
||||
const userRole = role || 'agente';
|
||||
const agenteId = userRole === 'admin' ? 0 : (agente_id || 0);
|
||||
|
||||
if (userRole === 'agente' && !agente_id) {
|
||||
return res.status(400).json({ error: 'Agente ID e obrigatorio para agentes' });
|
||||
}
|
||||
|
||||
const result = await createUser(email, senha, nome, userRole, agenteId);
|
||||
res.json({ success: true, id: result.lastInsertRowid });
|
||||
} catch (err) {
|
||||
console.error('Create user error:', err);
|
||||
if (err.message && err.message.includes('UNIQUE')) {
|
||||
return res.status(400).json({ error: 'E-mail ja cadastrado' });
|
||||
}
|
||||
res.status(500).json({ error: 'Erro ao criar usuario' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update user (admin only)
|
||||
app.put('/admin/agentes/:id', requireRole('admin'), async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { nome, email, agente_id, ativo, senha, role } = req.body;
|
||||
try {
|
||||
const agent = db.prepare('SELECT * FROM agentes WHERE id = ?').get(id);
|
||||
if (!agent) {
|
||||
return res.status(404).json({ error: 'Usuario nao encontrado' });
|
||||
}
|
||||
|
||||
if (senha) {
|
||||
const hash = await bcrypt.hash(senha, 10);
|
||||
db.prepare('UPDATE agentes SET senha_hash = ? WHERE id = ?').run(hash, id);
|
||||
}
|
||||
|
||||
if (nome !== undefined) {
|
||||
db.prepare('UPDATE agentes SET nome = ? WHERE id = ?').run(nome, id);
|
||||
}
|
||||
if (email !== undefined) {
|
||||
db.prepare('UPDATE agentes SET email = ? WHERE id = ?').run(email, id);
|
||||
}
|
||||
if (agente_id !== undefined) {
|
||||
db.prepare('UPDATE agentes SET agente_id = ? WHERE id = ?').run(agente_id, id);
|
||||
}
|
||||
if (ativo !== undefined) {
|
||||
db.prepare('UPDATE agentes SET ativo = ? WHERE id = ?').run(ativo, id);
|
||||
}
|
||||
if (role !== undefined) {
|
||||
db.prepare('UPDATE agentes SET role = ? WHERE id = ?').run(role, id);
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Update user error:', err);
|
||||
if (err.message && err.message.includes('UNIQUE')) {
|
||||
return res.status(400).json({ error: 'E-mail ja cadastrado' });
|
||||
}
|
||||
res.status(500).json({ error: 'Erro ao atualizar usuario' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete/deactivate user (admin only)
|
||||
app.delete('/admin/agentes/:id', requireRole('admin'), (req, res) => {
|
||||
const { id } = req.params;
|
||||
try {
|
||||
const result = db.prepare('UPDATE agentes SET ativo = 0 WHERE id = ?').run(id);
|
||||
if (result.changes === 0) {
|
||||
return res.status(404).json({ error: 'Usuario nao encontrado' });
|
||||
}
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
console.error('Delete user error:', err);
|
||||
res.status(500).json({ error: 'Erro ao desativar usuario' });
|
||||
}
|
||||
});
|
||||
|
||||
// Start
|
||||
app.listen(PORT, () => {
|
||||
console.log(`BI Agentes rodando: http://localhost:${PORT}`);
|
||||
console.log(`BI - CCC rodando: http://localhost:${PORT}`);
|
||||
});
|
||||
|
||||
37
src/admin-auth.js
Normal file
37
src/admin-auth.js
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Admin Authentication - login/logout with bcrypt + express-session
|
||||
*/
|
||||
const bcrypt = require('bcrypt');
|
||||
const db = require('./db-local');
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
async function createAdmin(email, senha, nome) {
|
||||
const hash = await bcrypt.hash(senha, SALT_ROUNDS);
|
||||
return db.prepare(
|
||||
'INSERT INTO admins (email, senha_hash, nome) VALUES (?, ?, ?)'
|
||||
).run(email, hash, nome);
|
||||
}
|
||||
|
||||
async function authenticateAdmin(email, senha) {
|
||||
const row = db.prepare(
|
||||
'SELECT * FROM admins WHERE email = ?'
|
||||
).get(email);
|
||||
if (!row) return null;
|
||||
const match = await bcrypt.compare(senha, row.senha_hash);
|
||||
return match ? row : null;
|
||||
}
|
||||
|
||||
function requireAdmin(req, res, next) {
|
||||
if (req.session && req.session.admin) return next();
|
||||
res.redirect('/admin/login');
|
||||
}
|
||||
|
||||
async function updateAdminPassword(id, novaSenha) {
|
||||
const hash = await bcrypt.hash(novaSenha, SALT_ROUNDS);
|
||||
return db.prepare(
|
||||
'UPDATE admins SET senha_hash = ? WHERE id = ?'
|
||||
).run(hash, id);
|
||||
}
|
||||
|
||||
module.exports = { createAdmin, authenticateAdmin, requireAdmin, updateAdminPassword };
|
||||
433
src/admin-home.js
Normal file
433
src/admin-home.js
Normal file
@@ -0,0 +1,433 @@
|
||||
/**
|
||||
* Admin Home Dashboard - Fast daily overview
|
||||
* 3 flows: BRL→USD, USD→BRL, USD→USD (balance)
|
||||
*/
|
||||
|
||||
function buildAdminHomeHTML(stats, admin) {
|
||||
const now = new Date().toLocaleString('pt-BR');
|
||||
const hoje = new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' });
|
||||
|
||||
const formatBRL = (v) => v.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
|
||||
const formatUSD = (v) => v.toLocaleString('pt-BR', { style: 'currency', currency: 'USD' });
|
||||
|
||||
// Calculate variations
|
||||
const calcVar = (hoje, ontem) => ontem > 0
|
||||
? ((hoje - ontem) / ontem * 100).toFixed(1)
|
||||
: (hoje > 0 ? 100 : 0);
|
||||
|
||||
const brlUsdVar = calcVar(stats.brlUsd.hoje.qtd, stats.brlUsd.ontem.qtd);
|
||||
const usdBrlVar = calcVar(stats.usdBrl.hoje.qtd, stats.usdBrl.ontem.qtd);
|
||||
const usdUsdVar = calcVar(stats.usdUsd.hoje.qtd, stats.usdUsd.ontem.qtd);
|
||||
|
||||
const totalHoje = stats.brlUsd.hoje.qtd + stats.usdBrl.hoje.qtd + stats.usdUsd.hoje.qtd;
|
||||
const totalOntem = stats.brlUsd.ontem.qtd + stats.usdBrl.ontem.qtd + stats.usdUsd.ontem.qtd;
|
||||
const totalVar = calcVar(totalHoje, totalOntem);
|
||||
|
||||
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 - Home</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #6C3FA0;
|
||||
--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;
|
||||
--purple: #7B1FA2;
|
||||
--purple-bg: #F3E5F5;
|
||||
--red: #D93025;
|
||||
--admin-accent: #2E7D32;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, sans-serif;
|
||||
background: var(--bg); color: var(--text); line-height: 1.5;
|
||||
}
|
||||
.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; }
|
||||
.header .subtitle { font-size: 13px; opacity: 0.8; margin-top: 4px; }
|
||||
.header-right { display: flex; align-items: center; gap: 12px; }
|
||||
.badge {
|
||||
background: rgba(255,255,255,0.15); padding: 8px 16px;
|
||||
border-radius: 24px; font-size: 12px; font-weight: 600;
|
||||
}
|
||||
.btn {
|
||||
padding: 8px 16px; border-radius: 8px; font-size: 12px; font-weight: 600;
|
||||
cursor: pointer; text-decoration: none; font-family: inherit;
|
||||
transition: all 0.15s; border: 1px solid rgba(255,255,255,0.3);
|
||||
background: rgba(255,255,255,0.15); color: white;
|
||||
}
|
||||
.btn:hover { background: rgba(255,255,255,0.25); }
|
||||
.btn-blue { background: #1A73E8; border-color: #1A73E8; }
|
||||
.btn-blue:hover { background: #1557B0; }
|
||||
|
||||
.container { padding: 28px 40px; max-width: 1600px; margin: 0 auto; }
|
||||
|
||||
.date-banner {
|
||||
background: var(--card); border-radius: 12px; padding: 16px 24px;
|
||||
margin-bottom: 24px; border: 1px solid var(--border);
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
}
|
||||
.date-banner h2 { font-size: 18px; font-weight: 700; text-transform: capitalize; }
|
||||
.date-banner .time { font-size: 13px; color: var(--text-secondary); }
|
||||
|
||||
.kpi-grid {
|
||||
display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.kpi-card {
|
||||
background: var(--card); border-radius: 16px; padding: 24px;
|
||||
border: 1px solid var(--border); box-shadow: 0 2px 8px rgba(0,0,0,0.04);
|
||||
}
|
||||
.kpi-card.highlight { border-left: 4px solid var(--admin-accent); }
|
||||
.kpi-card.brl-usd { border-left: 4px solid var(--blue); }
|
||||
.kpi-card.usd-brl { border-left: 4px solid var(--green); }
|
||||
.kpi-card.usd-usd { border-left: 4px solid var(--purple); }
|
||||
.kpi-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
|
||||
.kpi-label { font-size: 12px; font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.3px; }
|
||||
.kpi-badge {
|
||||
font-size: 11px; font-weight: 700; padding: 4px 10px; border-radius: 12px;
|
||||
}
|
||||
.kpi-badge.up { background: var(--green-bg); color: var(--green); }
|
||||
.kpi-badge.down { background: #FDE7E7; color: var(--red); }
|
||||
.kpi-badge.neutral { background: var(--blue-bg); color: var(--blue); }
|
||||
.kpi-value { font-size: 36px; font-weight: 800; color: var(--text); margin-bottom: 4px; }
|
||||
.kpi-sub { font-size: 13px; color: var(--text-muted); }
|
||||
|
||||
.charts-grid {
|
||||
display: grid; grid-template-columns: repeat(2, 1fr); gap: 24px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.chart-card {
|
||||
background: var(--card); border-radius: 16px; padding: 24px;
|
||||
border: 1px solid var(--border); box-shadow: 0 2px 8px rgba(0,0,0,0.04);
|
||||
}
|
||||
.chart-card h3 { font-size: 14px; font-weight: 700; margin-bottom: 20px; color: var(--text); }
|
||||
.chart-wrap { height: 280px; position: relative; }
|
||||
|
||||
.detail-grid {
|
||||
display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px;
|
||||
}
|
||||
.detail-card {
|
||||
background: var(--card); border-radius: 16px; padding: 24px;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
.detail-card h3 {
|
||||
font-size: 14px; font-weight: 700; margin-bottom: 16px;
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
}
|
||||
.detail-card h3 .icon {
|
||||
width: 28px; height: 28px; border-radius: 8px;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 14px;
|
||||
}
|
||||
.detail-card h3 .icon.out { background: var(--blue-bg); }
|
||||
.detail-card h3 .icon.in { background: var(--green-bg); }
|
||||
.detail-card h3 .icon.balance { background: var(--purple-bg); }
|
||||
.detail-row {
|
||||
display: flex; justify-content: space-between; padding: 10px 0;
|
||||
border-bottom: 1px solid #F3F4F6; font-size: 13px;
|
||||
}
|
||||
.detail-row:last-child { border-bottom: none; }
|
||||
.detail-label { color: var(--text-secondary); }
|
||||
.detail-value { font-weight: 600; color: var(--text); }
|
||||
.detail-value.green { color: var(--green); }
|
||||
.detail-value.red { color: var(--red); }
|
||||
|
||||
.nav-links {
|
||||
display: flex; gap: 12px; margin-top: 28px;
|
||||
}
|
||||
.nav-card {
|
||||
flex: 1; background: var(--card); border-radius: 12px; padding: 20px;
|
||||
border: 1px solid var(--border); text-decoration: none; color: var(--text);
|
||||
transition: all 0.15s; display: flex; align-items: center; gap: 16px;
|
||||
}
|
||||
.nav-card:hover { border-color: var(--admin-accent); box-shadow: 0 4px 12px rgba(46,125,50,0.1); }
|
||||
.nav-card .icon {
|
||||
width: 48px; height: 48px; border-radius: 12px; background: var(--green-bg);
|
||||
display: flex; align-items: center; justify-content: center; font-size: 24px;
|
||||
}
|
||||
.nav-card h4 { font-size: 14px; font-weight: 700; margin-bottom: 4px; }
|
||||
.nav-card p { font-size: 12px; color: var(--text-secondary); }
|
||||
|
||||
.footer { text-align: center; padding: 24px; font-size: 12px; color: var(--text-muted); }
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.kpi-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
.detail-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.container { padding: 20px; }
|
||||
.header { padding: 20px; flex-direction: column; gap: 12px; }
|
||||
.kpi-grid, .charts-grid { grid-template-columns: 1fr; }
|
||||
.nav-links { flex-direction: column; }
|
||||
}
|
||||
</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/agentes" class="btn">Gerenciar Agentes</a>
|
||||
<a href="/admin/dashboard" class="btn btn-blue">Dashboard Completo</a>
|
||||
<a href="/logout" class="btn">Sair</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="date-banner">
|
||||
<h2>${hoje}</h2>
|
||||
<div class="time">Atualizado: ${now}</div>
|
||||
</div>
|
||||
|
||||
<div class="kpi-grid">
|
||||
<div class="kpi-card highlight">
|
||||
<div class="kpi-header">
|
||||
<div class="kpi-label">Total de Ordens Hoje</div>
|
||||
<div class="kpi-badge ${Number(totalVar) >= 0 ? 'up' : 'down'}">${Number(totalVar) >= 0 ? '+' : ''}${totalVar}%</div>
|
||||
</div>
|
||||
<div class="kpi-value">${totalHoje}</div>
|
||||
<div class="kpi-sub">Ontem: ${totalOntem} ordens</div>
|
||||
</div>
|
||||
<div class="kpi-card brl-usd">
|
||||
<div class="kpi-header">
|
||||
<div class="kpi-label">BRL → USD</div>
|
||||
<div class="kpi-badge ${Number(brlUsdVar) >= 0 ? 'up' : 'down'}">${Number(brlUsdVar) >= 0 ? '+' : ''}${brlUsdVar}%</div>
|
||||
</div>
|
||||
<div class="kpi-value">${stats.brlUsd.hoje.qtd}</div>
|
||||
<div class="kpi-sub">Ontem: ${stats.brlUsd.ontem.qtd}</div>
|
||||
</div>
|
||||
<div class="kpi-card usd-brl">
|
||||
<div class="kpi-header">
|
||||
<div class="kpi-label">USD → BRL</div>
|
||||
<div class="kpi-badge ${Number(usdBrlVar) >= 0 ? 'up' : 'down'}">${Number(usdBrlVar) >= 0 ? '+' : ''}${usdBrlVar}%</div>
|
||||
</div>
|
||||
<div class="kpi-value">${stats.usdBrl.hoje.qtd}</div>
|
||||
<div class="kpi-sub">Ontem: ${stats.usdBrl.ontem.qtd}</div>
|
||||
</div>
|
||||
<div class="kpi-card usd-usd">
|
||||
<div class="kpi-header">
|
||||
<div class="kpi-label">USD → USD (Balance)</div>
|
||||
<div class="kpi-badge ${Number(usdUsdVar) >= 0 ? 'up' : 'down'}">${Number(usdUsdVar) >= 0 ? '+' : ''}${usdUsdVar}%</div>
|
||||
</div>
|
||||
<div class="kpi-value">${stats.usdUsd.hoje.qtd}</div>
|
||||
<div class="kpi-sub">Ontem: ${stats.usdUsd.ontem.qtd}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="charts-grid">
|
||||
<div class="chart-card">
|
||||
<h3>Quantidade de Ordens por Fluxo</h3>
|
||||
<div class="chart-wrap"><canvas id="chartQtd"></canvas></div>
|
||||
</div>
|
||||
<div class="chart-card">
|
||||
<h3>Volume USD por Fluxo</h3>
|
||||
<div class="chart-wrap"><canvas id="chartVol"></canvas></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-grid">
|
||||
<div class="detail-card">
|
||||
<h3><span class="icon out">→</span> BRL → USD (Remessas)</h3>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Hoje</span>
|
||||
<span class="detail-value">${stats.brlUsd.hoje.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Ontem</span>
|
||||
<span class="detail-value">${stats.brlUsd.ontem.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume BRL Hoje</span>
|
||||
<span class="detail-value">${formatBRL(stats.brlUsd.hoje.total_brl)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume USD Hoje</span>
|
||||
<span class="detail-value">${formatUSD(stats.brlUsd.hoje.total_usd)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Variacao</span>
|
||||
<span class="detail-value ${Number(brlUsdVar) >= 0 ? 'green' : 'red'}">${Number(brlUsdVar) >= 0 ? '+' : ''}${brlUsdVar}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-card">
|
||||
<h3><span class="icon in">←</span> USD → BRL (Recebimentos)</h3>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Hoje</span>
|
||||
<span class="detail-value">${stats.usdBrl.hoje.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Ontem</span>
|
||||
<span class="detail-value">${stats.usdBrl.ontem.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume BRL Hoje</span>
|
||||
<span class="detail-value">${formatBRL(stats.usdBrl.hoje.total_brl)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume USD Hoje</span>
|
||||
<span class="detail-value">${formatUSD(stats.usdBrl.hoje.total_usd)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Variacao</span>
|
||||
<span class="detail-value ${Number(usdBrlVar) >= 0 ? 'green' : 'red'}">${Number(usdBrlVar) >= 0 ? '+' : ''}${usdBrlVar}%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-card">
|
||||
<h3><span class="icon balance">↔</span> USD → USD (Balance)</h3>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Hoje</span>
|
||||
<span class="detail-value">${stats.usdUsd.hoje.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Ordens Ontem</span>
|
||||
<span class="detail-value">${stats.usdUsd.ontem.qtd}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume USD Hoje</span>
|
||||
<span class="detail-value">${formatUSD(stats.usdUsd.hoje.total_usd)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Volume USD Ontem</span>
|
||||
<span class="detail-value">${formatUSD(stats.usdUsd.ontem.total_usd)}</span>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span class="detail-label">Variacao</span>
|
||||
<span class="detail-value ${Number(usdUsdVar) >= 0 ? 'green' : 'red'}">${Number(usdUsdVar) >= 0 ? '+' : ''}${usdUsdVar}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="nav-links">
|
||||
<a href="/admin/dashboard" class="nav-card">
|
||||
<div class="icon">📈</div>
|
||||
<div>
|
||||
<h4>Dashboard Completo</h4>
|
||||
<p>Analise detalhada com graficos e filtros</p>
|
||||
</div>
|
||||
</a>
|
||||
<a href="/admin/agentes" class="nav-card">
|
||||
<div class="icon">👥</div>
|
||||
<div>
|
||||
<h4>Gerenciar Agentes</h4>
|
||||
<p>Cadastro, edicao e emulacao de agentes</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">BI - CCC - CambioReal Central Command</div>
|
||||
|
||||
<script>
|
||||
const stats = ${JSON.stringify(stats)};
|
||||
|
||||
// Chart: Quantidade
|
||||
new Chart(document.getElementById('chartQtd'), {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: ['BRL → USD', 'USD → BRL', 'USD → USD'],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Hoje',
|
||||
data: [stats.brlUsd.hoje.qtd, stats.usdBrl.hoje.qtd, stats.usdUsd.hoje.qtd],
|
||||
backgroundColor: ['#1A73E8', '#2E7D32', '#7B1FA2'],
|
||||
borderRadius: 6,
|
||||
barPercentage: 0.7
|
||||
},
|
||||
{
|
||||
label: 'Ontem',
|
||||
data: [stats.brlUsd.ontem.qtd, stats.usdBrl.ontem.qtd, stats.usdUsd.ontem.qtd],
|
||||
backgroundColor: ['#90CAF9', '#A5D6A7', '#CE93D8'],
|
||||
borderRadius: 6,
|
||||
barPercentage: 0.7
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { position: 'top', labels: { font: { size: 12, weight: 600 }, usePointStyle: true } }
|
||||
},
|
||||
scales: {
|
||||
y: { beginAtZero: true, grid: { color: '#F3F4F6' }, ticks: { font: { size: 11 } } },
|
||||
x: { grid: { display: false }, ticks: { font: { size: 11, weight: 600 } } }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Chart: Volume USD
|
||||
new Chart(document.getElementById('chartVol'), {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: ['BRL → USD', 'USD → BRL', 'USD → USD'],
|
||||
datasets: [
|
||||
{
|
||||
label: 'Hoje (USD)',
|
||||
data: [stats.brlUsd.hoje.total_usd, stats.usdBrl.hoje.total_usd, stats.usdUsd.hoje.total_usd],
|
||||
backgroundColor: ['#1A73E8', '#2E7D32', '#7B1FA2'],
|
||||
borderRadius: 6,
|
||||
barPercentage: 0.7
|
||||
},
|
||||
{
|
||||
label: 'Ontem (USD)',
|
||||
data: [stats.brlUsd.ontem.total_usd, stats.usdBrl.ontem.total_usd, stats.usdUsd.ontem.total_usd],
|
||||
backgroundColor: ['#90CAF9', '#A5D6A7', '#CE93D8'],
|
||||
borderRadius: 6,
|
||||
barPercentage: 0.7
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { position: 'top', labels: { font: { size: 12, weight: 600 }, usePointStyle: true } },
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
label: (ctx) => ctx.dataset.label + ': $' + ctx.raw.toLocaleString('en-US', { minimumFractionDigits: 2 })
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
grid: { color: '#F3F4F6' },
|
||||
ticks: {
|
||||
font: { size: 11 },
|
||||
callback: (v) => '$' + (v >= 1000 ? (v/1000).toFixed(0) + 'k' : v)
|
||||
}
|
||||
},
|
||||
x: { grid: { display: false }, ticks: { font: { size: 11, weight: 600 } } }
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = { buildAdminHomeHTML };
|
||||
536
src/admin-panel.js
Normal file
536
src/admin-panel.js
Normal 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')">×</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')">×</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 };
|
||||
66
src/auth.js
66
src/auth.js
@@ -1,18 +1,33 @@
|
||||
/**
|
||||
* Autenticação — login/logout com bcrypt + express-session
|
||||
* Autenticacao Unificada — login/logout com bcrypt + express-session
|
||||
* Suporta roles: 'agente' | 'admin'
|
||||
*/
|
||||
const bcrypt = require('bcrypt');
|
||||
const db = require('./db-local');
|
||||
|
||||
const SALT_ROUNDS = 10;
|
||||
|
||||
async function createAgente(email, senha, agenteId, nome) {
|
||||
/**
|
||||
* Cria um novo usuario (agente ou admin)
|
||||
*/
|
||||
async function createUser(email, senha, nome, role = 'agente', agenteId = 0) {
|
||||
const hash = await bcrypt.hash(senha, SALT_ROUNDS);
|
||||
return db.prepare(
|
||||
'INSERT INTO agentes (email, senha_hash, agente_id, nome) VALUES (?, ?, ?, ?)'
|
||||
).run(email, hash, agenteId, nome);
|
||||
'INSERT INTO agentes (email, senha_hash, agente_id, nome, role) VALUES (?, ?, ?, ?, ?)'
|
||||
).run(email, hash, agenteId, nome, role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria agente (retrocompatibilidade)
|
||||
*/
|
||||
async function createAgente(email, senha, agenteId, nome) {
|
||||
return createUser(email, senha, nome, 'agente', agenteId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Autentica usuario por email/senha
|
||||
* Retorna usuario com role ou null se invalido
|
||||
*/
|
||||
async function authenticate(email, senha) {
|
||||
const row = db.prepare(
|
||||
'SELECT * FROM agentes WHERE email = ? AND ativo = 1'
|
||||
@@ -22,9 +37,48 @@ async function authenticate(email, senha) {
|
||||
return match ? row : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware que verifica autenticacao e roles
|
||||
* Uso: requireRole() - qualquer usuario logado
|
||||
* requireRole('admin') - apenas admins
|
||||
* requireRole('agente', 'admin') - ambos
|
||||
*/
|
||||
function requireRole(...roles) {
|
||||
return (req, res, next) => {
|
||||
if (!req.session?.user) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
if (roles.length && !roles.includes(req.session.user.role)) {
|
||||
return res.status(403).send('Acesso negado');
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware simples - apenas verifica se esta logado
|
||||
* Retrocompatibilidade com requireAuth
|
||||
*/
|
||||
function requireAuth(req, res, next) {
|
||||
if (req.session && req.session.agente) return next();
|
||||
if (req.session && req.session.user) return next();
|
||||
res.redirect('/login');
|
||||
}
|
||||
|
||||
module.exports = { createAgente, authenticate, requireAuth };
|
||||
/**
|
||||
* Atualiza senha de usuario
|
||||
*/
|
||||
async function updatePassword(id, novaSenha) {
|
||||
const hash = await bcrypt.hash(novaSenha, SALT_ROUNDS);
|
||||
return db.prepare(
|
||||
'UPDATE agentes SET senha_hash = ? WHERE id = ?'
|
||||
).run(hash, id);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createUser,
|
||||
createAgente,
|
||||
authenticate,
|
||||
requireAuth,
|
||||
requireRole,
|
||||
updatePassword
|
||||
};
|
||||
|
||||
1427
src/dashboard.js
1427
src/dashboard.js
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* SQLite local — controle de agentes (auth + config)
|
||||
* Login unificado: todos os usuarios na tabela agentes com coluna 'role'
|
||||
*/
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
@@ -18,9 +19,41 @@ db.exec(`
|
||||
senha_hash TEXT NOT NULL,
|
||||
agente_id INTEGER NOT NULL,
|
||||
nome TEXT NOT NULL,
|
||||
role TEXT DEFAULT 'agente',
|
||||
ativo INTEGER DEFAULT 1,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
`);
|
||||
|
||||
// Add role column if it doesn't exist (migration for existing databases)
|
||||
try {
|
||||
db.exec(`ALTER TABLE agentes ADD COLUMN role TEXT DEFAULT 'agente'`);
|
||||
} catch (e) {
|
||||
// Column already exists, ignore
|
||||
}
|
||||
|
||||
// Legacy table - keep for reference but no longer used
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS admins (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT UNIQUE NOT NULL,
|
||||
senha_hash TEXT NOT NULL,
|
||||
nome TEXT NOT NULL,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
`);
|
||||
|
||||
// Migrate existing admins to agentes table with role='admin'
|
||||
const admins = db.prepare('SELECT * FROM admins').all();
|
||||
for (const admin of admins) {
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT OR IGNORE INTO agentes (email, senha_hash, nome, role, agente_id, ativo)
|
||||
VALUES (?, ?, ?, 'admin', 0, 1)
|
||||
`).run(admin.email, admin.senha_hash, admin.nome);
|
||||
} catch (e) {
|
||||
// Email already exists in agentes, skip
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = db;
|
||||
|
||||
Reference in New Issue
Block a user