feat: trading terminal live rates + fix spread negativo + fix USD→BRL

- Adiciona widget de cotações ao vivo (USD/BRL e EUR/BRL) com design
  estilo terminal de trading (dark theme, tipografia mono, glow effects)
- Proxy server-side /api/cotacao com cache 3s e token AwesomeAPI
- Auto-refresh a cada 3 segundos apenas quando a página está aberta
- Corrige cálculo de spread negativo: remove Math.abs() em USD→BRL
  e Math.max(0,...) no spread líquido
- Corrige seção USD→BRL que não aparecia (filtro status !== 'finalizado')
- Corrige valor_reais no fluxo USD→BRL: agora calcula valor * cotação
- Adiciona classe CSS spread-negative para destacar spreads negativos
- Bandeiras de fluxo (BR/US/EU) nos botões de compra e venda

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-10 22:30:43 -05:00
parent 1ad28f54dd
commit 7ee15ad5e5
12 changed files with 1285 additions and 436 deletions

View File

@@ -1,92 +1,72 @@
/**
* Gera HTML do dashboard — parametrizado por agente
* Updated: 2026-02-09 - 4 decimal places for spread
*/
const { buildHeader, buildFooter, buildHead } = require('./ui-template');
function buildHTML(data, agente, isAgentDashboard = true, diasPeriodo = null, asyncLoad = false, isEmulating = false) {
const now = new Date().toLocaleString('pt-BR');
const isAdminDash = diasPeriodo !== null;
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 — ${agente.nome}</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"><\/script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--primary: #7600be;
--primary-light: #9B2DE5;
--primary-dark: #5A0091;
--primary-bg: #F5EAFA;
--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;
}
* { 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(--primary) 0%, var(--primary-dark) 100%);
// When emulating, use the emulator's role if provided, otherwise default to admin
const emulatorRole = agente.emulatorRole || 'admin';
const role = isEmulating ? emulatorRole : (isAdminDash ? 'admin' : 'agente');
// Determine the back URL based on emulator's role
const backUrl = emulatorRole === 'corporate' ? '/corporate' : '/admin';
const pageScripts = `<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.7/dist/chart.umd.min.js"><\/script>`;
const dashboardCSS = `
/* Emulation Banner */
.emulation-banner {
background: linear-gradient(90deg, #FF6B35, #F7931E);
color: white;
box-shadow: 0 2px 8px rgba(74,37,112,0.3);
}
.header-inner {
max-width: 1600px;
margin: 0 auto;
padding: 16px 40px;
padding: 10px 24px;
text-align: center;
font-size: 13px;
font-weight: 600;
display: flex;
justify-content: space-between;
justify-content: center;
align-items: center;
gap: 16px;
}
.header-logo {
height: 36px;
width: auto;
background: white;
padding: 6px 12px;
border-radius: 8px;
}
.header h1 { font-size: 20px; font-weight: 800; letter-spacing: -0.5px; }
.header .subtitle { font-size: 12px; opacity: 0.8; margin-top: 2px; font-weight: 400; }
.header-right { display: flex; align-items: center; gap: 12px; }
.header .badge {
background: rgba(255,255,255,0.15); backdrop-filter: blur(10px);
padding: 6px 14px; border-radius: 20px; font-size: 11px; font-weight: 600;
border: 1px solid rgba(255,255,255,0.2);
}
.header .live-dot {
display: inline-block; width: 8px; height: 8px; background: #4ADE80;
border-radius: 50%; margin-right: 6px; animation: pulse 2s infinite;
}
.header .app-name-badge {
.emulation-banner a {
background: rgba(255,255,255,0.2);
padding: 6px 14px;
color: white;
padding: 6px 16px;
border-radius: 6px;
font-size: 14px;
font-weight: 800;
text-decoration: none;
font-size: 12px;
border: 1px solid rgba(255,255,255,0.3);
}
.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: 6px; font-size: 12px; font-weight: 600;
cursor: pointer; text-decoration: none; font-family: inherit; transition: all 0.15s;
.emulation-banner a:hover {
background: rgba(255,255,255,0.3);
}
/* Live Badge */
.live-badge {
background: rgba(255,255,255,0.15);
padding: 6px 14px;
border-radius: 20px;
font-size: 11px;
font-weight: 600;
border: 1px solid rgba(255,255,255,0.2);
margin-right: 12px;
}
.live-dot {
display: inline-block;
width: 8px;
height: 8px;
background: #4ADE80;
border-radius: 50%;
margin-right: 6px;
animation: pulse 2s infinite;
}
.btn-logout:hover { background: rgba(255,255,255,0.25); }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
/* Filters */
.filters {
background: var(--card); border-bottom: 1px solid var(--border);
background: var(--card);
border-bottom: 1px solid var(--border);
box-shadow: 0 1px 2px rgba(0,0,0,0.04);
}
.filters-inner {
@@ -124,6 +104,94 @@ function buildHTML(data, agente, isAgentDashboard = true, diasPeriodo = null, as
}
.btn-export:hover { background: #25a244; transform: translateY(-1px); }
/* Trading Terminal - Live Rates */
.trading-terminal {
background: linear-gradient(135deg, #0F1923 0%, #1A2332 50%, #0D1B2A 100%);
border-top: 1px solid rgba(0,255,136,0.15);
border-bottom: 1px solid rgba(0,255,136,0.15);
padding: 16px 40px;
position: relative;
overflow: hidden;
}
.trading-terminal::before {
content: '';
position: absolute; top: 0; left: 0; right: 0; height: 1px;
background: linear-gradient(90deg, transparent, rgba(0,255,136,0.3), transparent);
}
.trading-terminal::after {
content: '';
position: absolute; bottom: 0; left: 0; right: 0; height: 1px;
background: linear-gradient(90deg, transparent, rgba(0,255,136,0.3), transparent);
}
.live-rate-bar {
display: flex; align-items: center; justify-content: center; gap: 20px;
max-width: 1600px; margin: 0 auto;
}
.terminal-title {
font-size: 10px; font-weight: 700; color: rgba(0,255,136,0.6);
text-transform: uppercase; letter-spacing: 2px; margin-right: 8px;
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
}
.live-rate-dot {
width: 7px; height: 7px; border-radius: 50%; background: #00FF88;
display: inline-block; animation: blink 1.5s infinite;
box-shadow: 0 0 6px rgba(0,255,136,0.6);
}
@keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0.2; } }
.rate-pair-group {
display: flex; align-items: center; gap: 8px;
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.06);
border-radius: 8px; padding: 8px 14px;
}
.rate-pair-label {
font-size: 11px; font-weight: 800; color: rgba(255,255,255,0.35);
text-transform: uppercase; letter-spacing: 1px; writing-mode: vertical-rl;
text-orientation: mixed; font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
}
.live-rate-btn {
display: flex; flex-direction: column; align-items: center; gap: 1px;
padding: 8px 18px; border-radius: 6px; border: 1px solid transparent;
font-family: inherit; font-size: 14px; font-weight: 700; cursor: default;
transition: all 0.25s; min-width: 150px; justify-content: center;
position: relative;
}
.rate-flags { font-size: 9px; opacity: 0.5; letter-spacing: 1px; line-height: 1; }
.live-rate-btn.compra {
background: rgba(0,255,136,0.08); color: #00FF88;
border-color: rgba(0,255,136,0.2);
}
.live-rate-btn.compra:hover { background: rgba(0,255,136,0.14); }
.live-rate-btn.venda {
background: rgba(255,68,68,0.08); color: #FF4444;
border-color: rgba(255,68,68,0.2);
}
.live-rate-btn.venda:hover { background: rgba(255,68,68,0.14); }
.live-rate-btn .rate-value {
font-size: 22px; font-weight: 800; letter-spacing: -0.5px;
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
font-variant-numeric: tabular-nums;
text-shadow: 0 0 12px currentColor;
}
.live-rate-btn .rate-type {
font-size: 9px; text-transform: uppercase; letter-spacing: 1.5px;
opacity: 0.5; font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
}
.live-rate-btn.pulse .rate-value { animation: ratePulse 0.4s ease; }
@keyframes ratePulse {
0% { transform: scale(1); text-shadow: 0 0 12px currentColor; }
50% { transform: scale(1.06); text-shadow: 0 0 24px currentColor, 0 0 48px currentColor; }
100% { transform: scale(1); text-shadow: 0 0 12px currentColor; }
}
.rate-separator {
width: 1px; height: 40px; background: rgba(255,255,255,0.08);
}
.live-rate-time {
font-size: 10px; color: rgba(255,255,255,0.25);
font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
letter-spacing: 0.5px;
}
.container { padding: 28px 40px; max-width: 1600px; margin: 0 auto; }
.kpi-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 28px; }
@@ -206,7 +274,6 @@ function buildHTML(data, agente, isAgentDashboard = true, diasPeriodo = null, as
tbody tr:nth-child(even):hover { background: #F8F5FF; }
.num { text-align: right; }
.footer { text-align: center; padding: 20px; font-size: 12px; color: var(--text-muted); }
/* Portfolio Analysis Styles */
.section-title {
@@ -229,6 +296,7 @@ function buildHTML(data, agente, isAgentDashboard = true, diasPeriodo = null, as
.spread-high { background: var(--green-bg) !important; color: var(--green); font-weight: 600; }
.spread-medium { background: var(--orange-bg) !important; color: var(--orange); font-weight: 600; }
.spread-low { background: #FEE2E2 !important; color: #DC2626; font-weight: 600; }
.spread-negative { background: #DC2626 !important; color: #FFFFFF; font-weight: 700; }
/* Netting Chart Styles */
.netting-section { margin-top: 32px; }
@@ -303,44 +371,22 @@ function buildHTML(data, agente, isAgentDashboard = true, diasPeriodo = null, as
.portfolio-kpi-grid { grid-template-columns: 1fr; }
.netting-kpi-grid { grid-template-columns: 1fr; }
}
</style>
`;
return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
${buildHead('Dashboard', dashboardCSS, pageScripts)}
</head>
<body>
${isEmulating ? `
<div style="background:linear-gradient(90deg,#FF6B35,#F7931E);color:white;padding:12px 24px;text-align:center;font-size:13px;font-weight:600;display:flex;justify-content:center;align-items:center;gap:16px;">
<div class="emulation-banner">
<span>Modo Emulacao - Visualizando como: ${agente.nome}</span>
<a href="/admin" style="background:rgba(255,255,255,0.2);color:white;padding:6px 16px;border-radius:6px;text-decoration:none;font-size:12px;border:1px solid rgba(255,255,255,0.3);">Voltar ao BI - CCC</a>
<a href="${backUrl}">Voltar ao BI - CCC</a>
</div>
` : ''}
<div class="header">
<div class="header-inner">
<div style="display:flex;align-items:center;gap:16px;">
<img src="/public/logo.png" alt="CambioReal" class="header-logo">
<div>
<h1 style="display:flex;align-items:center;gap:10px;">
<span class="app-name-badge">BI - CCC</span>
${agente.nome}${agente.agente_id ? ` &mdash; #${agente.agente_id}` : ''}
</h1>
<div class="subtitle">Dashboard de Transacoes ${isAdminDash ? `(${data.length.toLocaleString('pt-BR')} registros)` : ''}</div>
</div>
</div>
<div class="header-right">
${isAdminDash ? `
<select onchange="window.location.href='/admin/dashboard?dias='+this.value" style="padding:8px 12px;border-radius:8px;border:1px solid rgba(255,255,255,0.3);background:rgba(255,255,255,0.1);color:white;font-size:13px;cursor:pointer;">
<option value="30" ${diasPeriodo === 30 ? 'selected' : ''}>30 dias</option>
<option value="60" ${diasPeriodo === 60 ? 'selected' : ''}>60 dias</option>
<option value="90" ${diasPeriodo === 90 ? 'selected' : ''}>90 dias</option>
<option value="180" ${diasPeriodo === 180 ? 'selected' : ''}>180 dias</option>
<option value="365" ${diasPeriodo === 365 ? 'selected' : ''}>1 ano</option>
</select>
<a href="/admin" class="btn-logout">Voltar</a>
` : ''}
<div class="badge"><span class="live-dot"></span>Ao vivo &mdash; ${now}</div>
<a href="/logout" class="btn-logout">Sair</a>
</div>
</div>
</div>
${buildHeader({ role, userName: agente.nome, activePage: 'dashboard', showNav: !isEmulating })}
<div class="filters">
<div class="filters-inner">
@@ -371,6 +417,45 @@ ${isEmulating ? `
</div>
</div>
<div class="trading-terminal">
<div class="live-rate-bar">
<span class="live-rate-dot"></span>
<span class="terminal-title">Live Rates</span>
<div class="rate-pair-group">
<span class="rate-pair-label">USD</span>
<button class="live-rate-btn compra">
<span class="rate-flags">\uD83C\uDDFA\uD83C\uDDF8 \u2192 \uD83C\uDDE7\uD83C\uDDF7</span>
<span class="rate-type">Compra</span>
<span class="rate-value" id="rateUsdCompra">--</span>
</button>
<button class="live-rate-btn venda">
<span class="rate-flags">\uD83C\uDDE7\uD83C\uDDF7 \u2192 \uD83C\uDDFA\uD83C\uDDF8</span>
<span class="rate-type">Venda</span>
<span class="rate-value" id="rateUsdVenda">--</span>
</button>
</div>
<div class="rate-separator"></div>
<div class="rate-pair-group">
<span class="rate-pair-label">EUR</span>
<button class="live-rate-btn compra">
<span class="rate-flags">\uD83C\uDDEA\uD83C\uDDFA \u2192 \uD83C\uDDE7\uD83C\uDDF7</span>
<span class="rate-type">Compra</span>
<span class="rate-value" id="rateEurCompra">--</span>
</button>
<button class="live-rate-btn venda">
<span class="rate-flags">\uD83C\uDDE7\uD83C\uDDF7 \u2192 \uD83C\uDDEA\uD83C\uDDFA</span>
<span class="rate-type">Venda</span>
<span class="rate-value" id="rateEurVenda">--</span>
</button>
</div>
<span class="live-rate-time" id="rateTime">--</span>
</div>
</div>
<div class="container">
<div class="kpi-grid" id="kpiGrid"></div>
@@ -451,7 +536,7 @@ ${isEmulating ? `
</div>
</div>
<div class="footer">BI - CCC &mdash; CambioReal Central Command &mdash; ${agente.nome}</div>
${buildFooter()}
<script>
let RAW_DATA = ${asyncLoad ? '[]' : JSON.stringify(data)};
@@ -470,6 +555,7 @@ const fmtBRL = v => v.toLocaleString('pt-BR', { style: 'currency', currency: 'BR
const fmtUSD = v => v.toLocaleString('pt-BR', { style: 'currency', currency: 'USD' });
const fmtNum = (v, d=2) => v.toLocaleString('pt-BR', { minimumFractionDigits: d, maximumFractionDigits: d });
const fmtPct = v => fmtNum(v, 2) + '%';
const fmtPct4 = v => fmtNum(v, 4) + '%'; // 4 decimal places for spread
// Loading overlay
function showLoading(msg) {
@@ -508,6 +594,36 @@ async function loadDataAsync() {
hideLoading();
}
// Live USD/BRL + EUR/BRL Rate
let _lastUsdBid = null, _lastUsdAsk = null, _lastEurBid = null, _lastEurAsk = null;
function pulseEl(el) { el.closest('.live-rate-btn').classList.add('pulse'); setTimeout(() => el.closest('.live-rate-btn').classList.remove('pulse'), 500); }
async function fetchLiveRate() {
try {
const resp = await fetch('/api/cotacao');
const json = await resp.json();
const usd = json.USDBRL;
const eur = json.EURBRL;
if (usd) {
const bid = parseFloat(usd.bid), ask = parseFloat(usd.ask);
const elC = document.getElementById('rateUsdCompra'), elV = document.getElementById('rateUsdVenda');
elC.textContent = bid.toFixed(4); elV.textContent = ask.toFixed(4);
if (_lastUsdBid !== null && bid !== _lastUsdBid) pulseEl(elC);
if (_lastUsdAsk !== null && ask !== _lastUsdAsk) pulseEl(elV);
_lastUsdBid = bid; _lastUsdAsk = ask;
}
if (eur) {
const bid = parseFloat(eur.bid), ask = parseFloat(eur.ask);
const elC = document.getElementById('rateEurCompra'), elV = document.getElementById('rateEurVenda');
elC.textContent = bid.toFixed(4); elV.textContent = ask.toFixed(4);
if (_lastEurBid !== null && bid !== _lastEurBid) pulseEl(elC);
if (_lastEurAsk !== null && ask !== _lastEurAsk) pulseEl(elV);
_lastEurBid = bid; _lastEurAsk = ask;
}
document.getElementById('rateTime').textContent = new Date().toLocaleTimeString('pt-BR');
} catch (e) { /* silently retry next cycle */ }
}
function startLiveRate() { fetchLiveRate(); setInterval(fetchLiveRate, 3000); }
function initDashboard() {
const clientes = [...new Set(RAW_DATA.map(r => r.cliente))].sort();
const sel = document.getElementById('filterCliente');
@@ -520,6 +636,7 @@ function initDashboard() {
document.getElementById('filterEnd').value = dates[dates.length - 1];
}
applyFilters();
startLiveRate();
}
(function init() {
@@ -537,6 +654,7 @@ function initDashboard() {
document.getElementById('filterEnd').value = dates[dates.length - 1];
}
applyFilters();
startLiveRate();
})();
function applyFilters() {
@@ -746,7 +864,7 @@ function exportCSV() {
const headers = ['Fluxo','Data/Hora','Cliente','Valor BRL','Valor USD','IOF %','IOF R$','PTAX','Taxa Cobrada','Spread','Spread %','Spread Liq %','Status'];
const rows = filtered.map(r => {
const spreadLiq = Math.max(0, r.spread_pct - 0.20);
const spreadLiq = r.spread_pct - 0.20;
return [
r.fluxo,
r.data_operacao || '',
@@ -758,8 +876,8 @@ function exportCSV() {
r.taxa_ptax.toFixed(4),
r.taxa_cobrada.toFixed(4),
r.spread_bruto.toFixed(4),
r.spread_pct.toFixed(2),
spreadLiq.toFixed(2),
r.spread_pct.toFixed(4),
spreadLiq.toFixed(4),
r.status || ''
].join(';');
});
@@ -781,18 +899,20 @@ function exportCSV() {
function calcSpreadLiquido(spreadPct) {
// Spread Líquido = Spread Cobrado - 0.20% (custo operacional)
const CUSTO_OPERACIONAL = 0.20;
return Math.max(0, spreadPct - CUSTO_OPERACIONAL);
return spreadPct - CUSTO_OPERACIONAL;
}
function getSpreadLiqClass(spreadLiq) {
if (spreadLiq < 0) return 'spread-negative';
if (spreadLiq >= 0.5) return 'spread-high';
if (spreadLiq >= 0.2) return 'spread-medium';
return 'spread-low';
}
function renderTable() {
const brlUsd = filtered.filter(r => r.fluxo === 'BRL \\u2192 USD');
const usdBrl = filtered.filter(r => r.fluxo === 'USD \\u2192 BRL');
// Filtrar apenas transações finalizadas
const brlUsd = filtered.filter(r => r.fluxo === 'BRL \\u2192 USD' && r.status === 'finalizado');
const usdBrl = filtered.filter(r => r.fluxo === 'USD \\u2192 BRL' && r.status && r.status !== '0000-00-00');
document.getElementById('tableTitle').textContent = 'Transacoes (' + filtered.length + ')';
@@ -806,8 +926,8 @@ function renderTable() {
<td class="num">\${fmtBRL(r.valor_reais)}</td><td class="num">\${fmtUSD(r.valor_dolar)}</td>
<td class="num">\${fmtPct(r.iof_pct)}</td><td class="num">\${fmtBRL(r.iof_valor_rs)}</td>
<td class="num">\${fmtNum(r.taxa_ptax, 4)}</td><td class="num">\${fmtNum(r.taxa_cobrada, 4)}</td>
<td class="num">\${fmtNum(r.spread_bruto, 4)}</td><td class="num">\${fmtPct(r.spread_pct)}</td>
<td class="num \${getSpreadLiqClass(spreadLiq)}">\${fmtPct(spreadLiq)}</td>
<td class="num">\${fmtNum(r.spread_bruto, 4)}</td><td class="num">\${fmtPct4(r.spread_pct)}</td>
<td class="num \${getSpreadLiqClass(spreadLiq)}">\${fmtPct4(spreadLiq)}</td>
<td>\${r.status || '-'}</td>
</tr>\`;
}).join('');
@@ -821,8 +941,8 @@ function renderTable() {
<td class="num">\${fmtBRL(r.valor_reais)}</td><td class="num">\${fmtUSD(r.valor_dolar)}</td>
<td class="num">\${fmtPct(r.iof_pct)}</td><td class="num">\${fmtBRL(r.iof_valor_rs)}</td>
<td class="num">\${fmtNum(r.taxa_ptax, 4)}</td><td class="num">\${fmtNum(r.taxa_cobrada, 4)}</td>
<td class="num">\${fmtNum(r.spread_bruto, 4)}</td><td class="num">\${fmtPct(r.spread_pct)}</td>
<td class="num \${getSpreadLiqClass(spreadLiq)}">\${fmtPct(spreadLiq)}</td>
<td class="num">\${fmtNum(r.spread_bruto, 4)}</td><td class="num">\${fmtPct4(r.spread_pct)}</td>
<td class="num \${getSpreadLiqClass(spreadLiq)}">\${fmtPct4(spreadLiq)}</td>
<td>\${r.status || '-'}</td>
</tr>\`;
}).join('');