Commit inicial: GTI Maquina Comercial

App local (Node + SQLite) para captura, tratamento e exportacao de leads
comerciais, com dashboard de gestao, login/usuarios e integracao Z-PRO.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
DESKTOP-F2O4A80\User
2026-07-12 14:22:21 -03:00
co-authored by Claude
commit b8d10b210c
78 changed files with 19781 additions and 0 deletions
+323
View File
@@ -0,0 +1,323 @@
/* GTI Máquina Comercial — tokens de design (paleta validada, light/dark) */
:root {
--page: #f9f9f7;
--surface: #fcfcfb;
--ink: #0b0b0b;
--ink-2: #52514e;
--muted: #898781;
--grid: #e1e0d9;
--border: rgba(11, 11, 11, 0.10);
--accent: #2a78d6; /* series-1 azul */
--accent-ink: #ffffff;
--bar: #5598e7; /* sequential 350 — barras de ranking */
--good: #0ca30c;
--good-text: #006300;
--warning: #fab219;
--critical: #d03b3b;
--shadow: 0 1px 3px rgba(11, 11, 11, 0.08);
}
@media (prefers-color-scheme: dark) {
:root {
--page: #0d0d0d;
--surface: #1a1a19;
--ink: #ffffff;
--ink-2: #c3c2b7;
--muted: #898781;
--grid: #2c2c2a;
--border: rgba(255, 255, 255, 0.10);
--accent: #3987e5;
--bar: #3987e5;
--good-text: #0ca30c;
--shadow: none;
}
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
background: var(--page);
color: var(--ink);
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
}
/* ---------- topo ---------- */
.topbar {
display: flex; align-items: center; gap: 20px;
padding: 10px 20px;
background: var(--surface);
border-bottom: 1px solid var(--grid);
position: sticky; top: 0; z-index: 20;
}
.brand { display: flex; align-items: baseline; gap: 8px; }
.brand-mark {
background: var(--accent); color: var(--accent-ink);
font-weight: 800; padding: 3px 9px; border-radius: 6px; letter-spacing: 0.5px;
}
.brand-name { font-weight: 600; color: var(--ink-2); }
.tabs { display: flex; gap: 4px; flex: 1; }
.tab {
border: none; background: none; color: var(--ink-2);
font: inherit; font-weight: 600; padding: 8px 16px;
border-radius: 8px; cursor: pointer;
}
.tab:hover { background: var(--grid); }
.tab.active { background: var(--accent); color: var(--accent-ink); }
main { max-width: 1280px; margin: 0 auto; padding: 16px 20px 60px; }
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* ---------- cartões e grades ---------- */
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: 12px;
padding: 16px 18px;
box-shadow: var(--shadow);
margin-bottom: 16px;
}
.card h2 { margin: 0 0 12px; font-size: 16px; }
.captura-wrap { max-width: 720px; margin: 0 auto; }
.grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
@media (max-width: 1100px) {
.grid-3 { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 980px) {
.grid-3 { grid-template-columns: 1fr; }
}
/* ---------- formulários ---------- */
.field { margin-bottom: 18px; }
.field > label:first-child, .field > summary { font-weight: 600; display: block; margin-bottom: 6px; }
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.row.space-between { justify-content: space-between; }
.row.wrap { flex-wrap: wrap; }
.radio { display: flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; margin: 4px 0; }
select, input, textarea {
font: inherit; color: var(--ink);
background: var(--page);
border: 1px solid var(--grid);
border-radius: 8px; padding: 7px 10px;
}
select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
input[type="number"] { width: 90px; }
label > input[type="number"] { display: block; margin-top: 4px; }
details summary { cursor: pointer; }
.btn, .btn-ghost, .btn-danger {
font: inherit; font-weight: 600; cursor: pointer;
border-radius: 8px; padding: 8px 14px;
border: 1px solid var(--grid);
background: var(--surface); color: var(--ink);
}
.btn:hover, .btn-ghost:hover { border-color: var(--accent); }
.btn-primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
.btn-primary:hover { filter: brightness(1.1); }
.btn-lg { width: 100%; padding: 12px; font-size: 15px; }
.btn-ghost { border-color: transparent; color: var(--ink-2); }
.btn-danger { color: var(--critical); border-color: var(--critical); background: none; }
.btn-danger:hover { background: var(--critical); color: #fff; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.zona-risco { border: 1px solid var(--critical); border-radius: 10px; padding: 10px 12px; margin-top: 14px; }
.zona-risco label { color: var(--critical); font-weight: 700; }
/* ---------- login ---------- */
.login-body { display: flex; min-height: 100vh; }
.login-wrap { margin: auto; width: 100%; max-width: 360px; padding: 20px; }
.login-card { display: flex; flex-direction: column; gap: 14px; }
.login-brand { justify-content: center; margin-bottom: 4px; }
.login-erro { color: var(--critical); min-height: 1em; margin: 0; }
/* ---------- usuarios ---------- */
#lista-usuarios { display: flex; flex-direction: column; gap: 6px; margin-bottom: 14px; }
#lista-usuarios > div { padding: 6px 0; border-bottom: 1px solid var(--grid); }
#form-novo-usuario select { border: 1px solid var(--grid); border-radius: 8px; padding: 7px 10px; background: var(--surface); color: var(--ink); }
.chip {
font-size: 12px; font-weight: 600;
padding: 3px 10px; border-radius: 999px;
background: var(--grid); color: var(--ink-2);
}
.chip.ok { background: color-mix(in srgb, var(--good) 15%, transparent); color: var(--good-text); }
.chip.warn { background: color-mix(in srgb, var(--warning) 20%, transparent); color: var(--ink); }
.notice {
margin-top: 10px; padding: 12px;
border: 1px solid var(--warning);
border-radius: 8px;
background: color-mix(in srgb, var(--warning) 8%, transparent);
}
.notice p { margin: 0 0 10px; }
/* pickers de cidade/nicho */
.picker { margin-top: 8px; }
.picker input[type="search"] { width: 100%; margin-bottom: 6px; }
.sugestoes { display: flex; flex-direction: column; gap: 2px; max-height: 180px; overflow-y: auto; }
.sugestoes button {
text-align: left; font: inherit; border: none; background: none;
color: var(--ink); padding: 6px 8px; border-radius: 6px; cursor: pointer;
}
.sugestoes button:hover { background: var(--grid); }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.chips .chip { cursor: pointer; }
.chips .chip::after { content: " ✕"; color: var(--muted); }
.nichos-grid {
display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
gap: 2px 12px; max-height: 300px; overflow-y: auto; margin-top: 8px;
}
.nichos-grid label { display: flex; gap: 6px; align-items: center; padding: 3px 4px; border-radius: 6px; cursor: pointer; }
.nichos-grid label:hover { background: var(--grid); }
.cnae-avulso { margin-top: 10px; border-top: 1px dashed var(--grid); padding-top: 10px; }
.cnae-avulso summary { cursor: pointer; font-size: 13px; color: var(--ink-2); font-weight: 600; }
.cnae-avulso-hint { margin: 6px 0 8px; font-size: 12.5px; }
.cnae-avulso input[type="search"] { width: 100%; margin-bottom: 6px; }
.cnae-avulso .sugestoes button { display: flex; justify-content: space-between; gap: 8px; }
.cnae-avulso .sugestoes .cod { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 12px; }
.fontes { display: flex; flex-direction: column; gap: 6px; }
.fonte {
display: flex; gap: 10px; align-items: flex-start;
border: 1px solid var(--grid); border-radius: 8px; padding: 8px 10px; cursor: pointer;
}
.fonte input { margin-top: 3px; }
.fonte .desc { font-size: 12.5px; color: var(--ink-2); }
.fonte.indisponivel { opacity: 0.55; }
/* ---------- progresso ---------- */
.progress-bar { height: 8px; border-radius: 999px; background: var(--grid); overflow: hidden; margin: 10px 0 8px; }
.progress-fill { height: 100%; width: 3%; background: var(--accent); border-radius: 999px; transition: width 0.4s; }
.progress-msg { color: var(--ink-2); margin: 4px 0 10px; min-height: 1.4em; }
.stat-row { display: flex; gap: 18px; margin-bottom: 10px; }
.stat-row .mini { display: flex; flex-direction: column; }
.stat-row .mini b { font-size: 20px; }
.stat-row .mini span { font-size: 12px; color: var(--muted); }
.log {
font: 12px/1.5 ui-monospace, Consolas, monospace;
background: var(--page); border: 1px solid var(--grid); border-radius: 8px;
padding: 8px 10px; max-height: 160px; overflow-y: auto; white-space: pre-wrap;
}
.lista { display: flex; flex-direction: column; gap: 8px; }
.lista .item {
display: flex; justify-content: space-between; align-items: center; gap: 10px;
border-bottom: 1px solid var(--grid); padding: 8px 2px; flex-wrap: wrap;
}
.lista .item:last-child { border-bottom: none; }
.lista .item .sub { font-size: 12px; color: var(--muted); }
/* ---------- tratamento: tiles e rankings ---------- */
.filtros-card { padding: 12px 16px; }
.filtros { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
.filtros select, .filtros input { min-width: 130px; }
#f-busca { flex: 1; min-width: 200px; }
.stat-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 16px; }
.tile {
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
padding: 14px 16px; box-shadow: var(--shadow);
}
.tile .valor { font-size: 26px; font-weight: 700; }
.tile .rotulo { font-size: 12.5px; color: var(--ink-2); margin-top: 2px; }
.tile .detalhe { font-size: 12px; color: var(--muted); }
.tile.t-good .valor { color: var(--good-text); }
.tile.t-warn .valor { color: var(--ink); }
.tile.tile-wide { grid-column: span 2; }
@media (max-width: 640px) { .tile.tile-wide { grid-column: span 1; } }
.meta-input { width: 70px; text-align: right; padding: 3px 6px; border-radius: 6px; border: 1px solid var(--border); background: var(--surface); color: var(--ink); }
/* ---------- funil comercial ---------- */
.funil { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }
.funil-etapa { display: grid; grid-template-columns: 190px 1fr 70px; align-items: center; gap: 8px; padding: 1px 4px; }
.funil-etapa.pendente { opacity: 0.4; }
.funil-label { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.funil-barra { height: 14px; border-radius: 4px; overflow: hidden; background: none; }
.funil-fill { height: 100%; background: var(--bar); border-radius: 0 4px 4px 0; min-width: 2px; }
.funil-valor { font-size: 12.5px; color: var(--ink-2); text-align: right; font-variant-numeric: tabular-nums; }
/* barras de ranking: magnitude = um matiz (azul), rótulo direto, sem legenda */
.ranking { display: flex; flex-direction: column; gap: 7px; }
.rank-row { display: grid; grid-template-columns: 150px 1fr 70px; gap: 8px; align-items: center; cursor: pointer; border-radius: 6px; padding: 1px 4px; }
.rank-row:hover { background: var(--grid); }
.rank-row.ativo { background: color-mix(in srgb, var(--accent) 16%, transparent); font-weight: 600; }
.rank-row.nao-clicavel { cursor: default; }
.rank-row.nao-clicavel:hover { background: none; }
.oportunidade-clicavel { cursor: pointer; border-radius: 8px; padding: 6px 8px; }
.oportunidade-clicavel:hover { background: var(--grid); }
.oportunidade-clicavel.ativo { background: color-mix(in srgb, var(--accent) 16%, transparent); }
.rank-label { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.rank-track { height: 14px; border-radius: 4px; overflow: hidden; background: none; }
.rank-fill { height: 100%; background: var(--bar); border-radius: 0 4px 4px 0; min-width: 2px; }
.rank-value { font-size: 12.5px; color: var(--ink-2); text-align: right; font-variant-numeric: tabular-nums; }
/* ---------- tabela ---------- */
.table-wrap { overflow-x: auto; margin: 0 -4px; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--grid); white-space: nowrap; }
th { font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; color: var(--muted); }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
tbody tr { cursor: pointer; }
tbody tr:hover { background: color-mix(in srgb, var(--accent) 6%, transparent); }
.badge { font-size: 12px; font-weight: 600; padding: 2px 8px; border-radius: 999px; white-space: nowrap; }
/* Escala sequencial ordinal (excelente -> muito baixo), verde -> ambar -> vermelho,
construida so com os tokens ja validados (--good/--warning/--critical). */
.badge.excelente { background: color-mix(in srgb, var(--good) 20%, transparent); color: var(--good-text); }
.badge.bom { background: color-mix(in srgb, var(--good) 12%, var(--warning) 8%); color: var(--good-text); }
.badge.medio { background: color-mix(in srgb, var(--warning) 22%, transparent); color: var(--ink); }
.badge.baixo { background: color-mix(in srgb, var(--warning) 18%, var(--critical) 12%); color: var(--critical); }
.badge.muito_baixo { background: color-mix(in srgb, var(--critical) 16%, transparent); color: var(--critical); }
.badge.prioridade-1 { background: color-mix(in srgb, var(--good) 20%, transparent); color: var(--good-text); }
.badge.prioridade-2 { background: color-mix(in srgb, var(--warning) 22%, transparent); color: var(--ink); }
.badge.prioridade-3 { background: var(--grid); color: var(--ink-2); }
.badge.prioridade-4 { background: var(--grid); color: var(--muted); }
.produto-cell { font-size: 12.5px; }
.estrelas { color: var(--warning); letter-spacing: 1px; white-space: nowrap; }
.pontos-fortes { list-style: none; margin: 6px 0 0; padding: 0; display: flex; flex-direction: column; gap: 3px; font-size: 13px; }
.resumo-comercial { border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; margin-top: 12px; }
.resumo-comercial h3 { margin: 0 0 8px; font-size: 14px; }
.empresa-cell { max-width: 280px; overflow: hidden; text-overflow: ellipsis; }
/* ---------- explicacao de score (v2.1) ---------- */
.score-breakdown-wrap { border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; margin-top: 12px; }
.score-breakdown { list-style: none; margin: 6px 0 0; padding: 0; display: flex; flex-direction: column; gap: 3px; font-size: 13px; }
.score-breakdown li.ok { color: var(--ink); }
.score-breakdown li.nok { color: var(--muted); }
/* ---------- atalhos de exportacao (v2.1) ---------- */
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 12px; }
.chip {
border: 1px solid var(--border); background: var(--surface); color: var(--ink);
border-radius: 999px; padding: 4px 12px; font-size: 12.5px; cursor: pointer;
}
.chip:hover { background: var(--grid); border-color: var(--accent); }
/* ---------- modais e toast ---------- */
dialog {
border: 1px solid var(--border); border-radius: 14px;
background: var(--surface); color: var(--ink);
max-width: 560px; width: calc(100vw - 40px);
padding: 0;
}
dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal-body { padding: 20px 22px; }
.modal-body h2 { margin-top: 0; }
#modal-historico { max-width: 620px; }
#modal-historico .lista { max-height: 60vh; overflow-y: auto; margin-top: 10px; }
textarea { width: 100%; resize: vertical; }
.toast {
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
background: var(--ink); color: var(--page);
padding: 10px 18px; border-radius: 10px; font-weight: 600;
z-index: 100; max-width: 80vw;
}
.hidden { display: none !important; }
.muted { color: var(--muted); font-weight: 400; }
/* detalhe do lead */
.detalhe-grid { display: grid; grid-template-columns: 140px 1fr; gap: 4px 12px; font-size: 13.5px; }
.detalhe-grid dt { color: var(--muted); }
.detalhe-grid dd { margin: 0; word-break: break-word; }
+360
View File
@@ -0,0 +1,360 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GTI Máquina Comercial</title>
<link rel="stylesheet" href="/css/app.css">
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🎯</text></svg>">
</head>
<body>
<header class="topbar">
<div class="brand">
<span class="brand-mark">GTI</span>
<span class="brand-name">Máquina Comercial</span>
</div>
<nav class="tabs" role="tablist">
<button class="tab active" data-tab="captura" role="tab" aria-selected="true">📡 Capturar Leads</button>
<button class="tab" data-tab="tratamento" role="tab" aria-selected="false">📊 Tratar Leads</button>
</nav>
<span class="muted" id="usuario-logado"></span>
<button class="btn-ghost hidden" id="btn-usuarios" title="Usuários">👤 Usuários</button>
<button class="btn-ghost" id="btn-settings" title="Configurações">⚙️</button>
<button class="btn-ghost" id="btn-sair" title="Sair">🚪 Sair</button>
</header>
<main>
<!-- ==================== CAPTURA ==================== -->
<section id="tab-captura" class="tab-panel active">
<div class="captura-wrap">
<div class="card" id="captura-form">
<div class="row space-between">
<h2>Nova captura</h2>
<button class="btn-ghost" id="btn-ver-historico" type="button">🕓 Histórico de capturas</button>
</div>
<div class="field">
<label for="sel-uf">1. Estado (UF)</label>
<div class="row">
<select id="sel-uf"></select>
<span id="uf-status" class="chip"></span>
</div>
<div id="extracao-aviso" class="notice hidden">
<p>A base CNPJ de <strong id="extracao-uf"></strong> ainda não foi extraída neste computador.
A extração lê os arquivos da Receita Federal e demora <strong>~40 a 60 minutos</strong> (uma única vez por estado).</p>
<button class="btn" id="btn-extrair">⛏️ Extrair base agora</button>
</div>
</div>
<div class="field">
<label>2. Cidades</label>
<div class="row">
<label class="radio"><input type="radio" name="cidades-modo" value="todas" checked> Todas as cidades da UF</label>
<label class="radio"><input type="radio" name="cidades-modo" value="escolher"> Escolher cidades</label>
</div>
<div id="cidades-picker" class="picker hidden">
<input type="search" id="busca-cidade" placeholder="Digite para buscar cidade...">
<div id="cidades-sugestoes" class="sugestoes"></div>
<div id="cidades-chips" class="chips"></div>
</div>
</div>
<div class="field">
<label>3. Nichos <span class="muted" id="nichos-contagem"></span></label>
<div class="row">
<label class="radio"><input type="radio" name="nichos-modo" value="todos" checked> Todos os nichos</label>
<label class="radio"><input type="radio" name="nichos-modo" value="escolher"> Escolher nichos</label>
</div>
<div id="nichos-picker" class="picker hidden">
<div class="row">
<input type="search" id="busca-nicho" placeholder="Filtrar nichos...">
<button class="btn-ghost" id="btn-nichos-todos" type="button">Marcar visíveis</button>
<button class="btn-ghost" id="btn-nichos-nenhum" type="button">Desmarcar todos</button>
</div>
<div id="nichos-grid" class="nichos-grid"></div>
</div>
<details class="cnae-avulso">
<summary>Não achou o nicho? Buscar qualquer atividade da Receita Federal (CNAE)</summary>
<p class="muted cnae-avulso-hint">Os 57 nichos acima já vêm com mensagem e interesse configurados. Um CNAE avulso é adicionado só para a busca — ele participa da captura normalmente.</p>
<input type="search" id="busca-cnae" placeholder="Ex.: salão de beleza, transportadora, escola...">
<div id="cnae-sugestoes" class="sugestoes"></div>
<div id="cnae-chips" class="chips"></div>
</details>
</div>
<div class="field">
<label>4. Fontes de busca</label>
<div id="fontes-lista" class="fontes"></div>
</div>
<details class="field">
<summary>Opções avançadas</summary>
<div class="row">
<label>Máx. por consulta (fontes de API)
<input type="number" id="inp-max" value="10" min="1" max="60">
</label>
<label>Limite total de consultas (0 = sem limite)
<input type="number" id="inp-query-limit" value="0" min="0">
</label>
</div>
</details>
<button class="btn btn-primary btn-lg" id="btn-capturar">🚀 Iniciar captura</button>
</div>
<div class="card hidden" id="progresso-card">
<div class="row space-between">
<h2 id="progresso-titulo">Captura em andamento</h2>
<button class="btn-danger" id="btn-cancelar">Cancelar</button>
</div>
<div class="progress-bar"><div class="progress-fill" id="progresso-fill"></div></div>
<p class="progress-msg" id="progresso-msg">iniciando...</p>
<div class="stat-row" id="progresso-stats"></div>
<div class="log" id="progresso-log"></div>
</div>
</div>
</section>
<!-- ==================== TRATAMENTO ==================== -->
<section id="tab-tratamento" class="tab-panel">
<div class="card filtros-card">
<div class="filtros" id="filtros">
<select id="f-uf" data-filtro="uf"><option value="">UF: todas</option></select>
<input list="dl-cidades" id="f-cidade" data-filtro="cidade" placeholder="Cidade: todas">
<datalist id="dl-cidades"></datalist>
<select id="f-segmento" data-filtro="segmento"><option value="">Nicho: todos</option></select>
<select id="f-classificacao" data-filtro="classificacao">
<option value="">Classificação: todas</option>
<option value="excelente">🟢 Excelente</option>
<option value="bom">🟢 Bom</option>
<option value="medio">🟡 Médio</option>
<option value="baixo">🟠 Baixo</option>
<option value="muito_baixo">🔴 Muito Baixo</option>
</select>
<select id="f-prioridade" data-filtro="prioridade">
<option value="">Prioridade: todas</option>
<option value="1">P1 — atacar agora</option>
<option value="2">P2 — esta semana</option>
<option value="3">P3 — quando sobrar</option>
<option value="4">P4 — campanhas específicas</option>
</select>
<select id="f-produto" data-filtro="produto"><option value="">Produto: todos</option></select>
<select id="f-interesse" data-filtro="interesse"><option value="">Interesse: todos</option></select>
<select id="f-telefone" data-filtro="telefone_valido">
<option value="">WhatsApp: todos</option>
<option value="sim">Com WhatsApp</option>
<option value="nao">Sem WhatsApp</option>
</select>
<select id="f-website" data-filtro="website">
<option value="">Website: todos</option>
<option value="sim">Com website</option>
<option value="nao">Sem website</option>
</select>
<select id="f-email" data-filtro="email">
<option value="">E-mail: todos</option>
<option value="sim">Com e-mail</option>
<option value="nao">Sem e-mail</option>
</select>
<select id="f-exportado" data-filtro="exportado">
<option value="">Exportação: todos</option>
<option value="nao">Ainda não exportados</option>
<option value="sim">Já exportados</option>
</select>
<input type="search" id="f-busca" data-filtro="q" placeholder="🔎 empresa, CNPJ ou WhatsApp">
<button class="btn-ghost" id="btn-limpar-filtros">Limpar</button>
</div>
</div>
<div class="stat-tiles" id="stat-tiles"></div>
<div class="grid-3">
<div class="card">
<div class="row space-between">
<h2>Top cidades</h2>
</div>
<div id="rank-cidades" class="ranking"></div>
</div>
<div class="card">
<div class="row space-between">
<h2>Top nichos</h2>
</div>
<div id="rank-segmentos" class="ranking"></div>
</div>
<div class="card">
<div class="row space-between">
<h2 id="rank-produtos-titulo">Top produto recomendado</h2>
</div>
<div id="rank-produtos" class="ranking"></div>
</div>
</div>
<div class="grid-3">
<div class="card" id="card-oportunidades-dia"></div>
<div class="card" id="card-maior-oportunidade"></div>
<div class="card" id="card-evolucao-diaria"></div>
</div>
<div class="card" id="card-funil"></div>
<div class="card">
<div class="row space-between wrap">
<h2>Leads <span class="muted" id="leads-total"></span></h2>
<button class="btn btn-primary" id="btn-exportar">📤 Gerar relatório / exportação com este filtro</button>
</div>
<div class="table-wrap">
<table id="tabela-leads">
<thead>
<tr>
<th>Empresa</th><th>WhatsApp</th><th>Cidade</th><th>Nicho</th>
<th>Prioridade</th><th class="num">Geral</th>
<th>Classificação</th><th>Produto</th><th>Exportado</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row space-between">
<button class="btn-ghost" id="pg-prev">← Anterior</button>
<span class="muted" id="pg-info"></span>
<button class="btn-ghost" id="pg-next">Próxima →</button>
</div>
</div>
<div class="card">
<h2>Exportações geradas</h2>
<div id="historico-exports" class="lista"></div>
</div>
</section>
</main>
<!-- Modal de exportação -->
<dialog id="modal-export">
<form method="dialog" class="modal-body" id="form-export">
<h2>Gerar relatório / exportação</h2>
<p class="muted" id="export-recap"></p>
<div id="export-atalhos" class="chips"></div>
<div class="field">
<label>Tipo de arquivo</label>
<label class="radio"><input type="radio" name="export-tipo" value="excel" checked>
📊 <strong>Planilha (CSV + Excel)</strong> — lista completa com score, à prova de notação científica</label>
<label class="radio"><input type="radio" name="export-tipo" value="zpro-oportunidades">
🗂️ <strong>Z-PRO: Oportunidades (JSONL)</strong> — payloads prontos para createOpportunity</label>
<label class="radio"><input type="radio" name="export-tipo" value="zpro-bulk">
📨 <strong>Z-PRO: Disparo em massa (CSV)</strong> — dataInput para BulkSendMessageWithVariable</label>
</div>
<div class="field" id="export-zpro-params">
<label>Parâmetros Z-PRO</label>
<div class="row">
<label>Pipeline <input type="number" id="zp-pipeline" min="1"></label>
<label>Etapa <input type="number" id="zp-stage" min="1"></label>
<label>Responsável <input type="number" id="zp-responsible" min="1"></label>
</div>
</div>
<div class="field hidden" id="export-mensagem-wrap">
<label>Mensagem sugerida (use {empresa}, {cidade}, {segmento})</label>
<textarea id="export-mensagem" rows="3">Olá {empresa}! Somos do Grupo GTI e ajudamos empresas de {cidade} com sistema de gestão, TI e atendimento automático no WhatsApp. Podemos conversar?</textarea>
</div>
<label class="radio"><input type="checkbox" id="export-marcar" checked>
Marcar estes leads como exportados (não aparecem de novo no filtro "ainda não exportados")</label>
<div class="row space-between">
<button class="btn-ghost" value="cancel">Cancelar</button>
<button class="btn btn-primary" id="btn-confirmar-export" value="default">Gerar arquivos</button>
</div>
</form>
</dialog>
<!-- Modal de histórico de capturas -->
<dialog id="modal-historico">
<div class="modal-body">
<div class="row space-between">
<h2>Últimas capturas</h2>
<button class="btn-ghost" id="btn-fechar-historico" type="button">Fechar</button>
</div>
<div id="historico-capturas" class="lista"></div>
</div>
</dialog>
<!-- Modal de configurações -->
<dialog id="modal-settings">
<form method="dialog" class="modal-body">
<h2>Configurações</h2>
<div class="field">
<label>Padrões Z-PRO (usados nas exportações)</label>
<div class="row">
<label>Pipeline <input type="number" id="cfg-pipeline" min="1"></label>
<label>Etapa <input type="number" id="cfg-stage" min="1"></label>
<label>Responsável <input type="number" id="cfg-responsible" min="1"></label>
</div>
<div class="row">
<label>Previsão de fechamento (dias) <input type="number" id="cfg-forecast" min="1"></label>
</div>
</div>
<div class="field zona-risco">
<label>Zona de risco</label>
<p class="muted">Apaga permanentemente todos os leads, exportações, capturas e extrações. Configurações e nichos não são afetados.</p>
<button class="btn-danger" id="btn-limpar-base" type="button">🗑️ Limpar toda a base de leads</button>
</div>
<div class="row space-between">
<button class="btn-ghost" value="cancel">Fechar</button>
<button class="btn btn-primary" id="btn-salvar-settings" value="default">Salvar</button>
</div>
</form>
</dialog>
<!-- Modal de confirmacao da limpeza total da base -->
<dialog id="modal-reset-base">
<div class="modal-body">
<h2>Limpar toda a base de leads</h2>
<p class="muted">Esta ação é <strong>irreversível</strong>: todos os leads, exportações, capturas e extrações serão apagados. Digite a senha de segurança para confirmar.</p>
<div class="field">
<label>Senha de segurança <input type="password" id="reset-base-senha" autocomplete="off"></label>
</div>
<div class="row space-between">
<button class="btn-ghost" id="btn-cancelar-reset-base" type="button">Cancelar</button>
<button class="btn-danger" id="btn-confirmar-reset-base" type="button">Confirmar limpeza</button>
</div>
</div>
</dialog>
<!-- Modal de usuarios (somente admin) -->
<dialog id="modal-usuarios">
<div class="modal-body">
<div class="row space-between">
<h2>Usuários</h2>
<button class="btn-ghost" id="btn-fechar-usuarios" type="button">Fechar</button>
</div>
<div id="lista-usuarios" class="lista"></div>
<form class="field" id="form-novo-usuario">
<label>Novo usuário</label>
<div class="row">
<input type="text" id="novo-usuario-username" placeholder="usuário" minlength="3" required>
<input type="password" id="novo-usuario-password" placeholder="senha" minlength="4" required>
<select id="novo-usuario-role">
<option value="comercial">Comercial</option>
<option value="admin">Administrador</option>
</select>
<button class="btn btn-primary" type="submit">Criar</button>
</div>
</form>
</div>
</dialog>
<!-- Modal detalhe do lead -->
<dialog id="modal-lead">
<div class="modal-body" id="lead-detalhe"></div>
</dialog>
<div id="toast" class="toast hidden"></div>
<script src="/js/api.js"></script>
<script src="/js/captura.js"></script>
<script src="/js/tratamento.js"></script>
<script src="/js/app.js"></script>
</body>
</html>
+94
View File
@@ -0,0 +1,94 @@
/* Cliente da API local + utilitários compartilhados. */
// 401 fora da tela de login = sessao expirada/inexistente: manda pro login.
function redirecionaSeSessaoExpirou(path, status) {
if (status === 401 && path !== '/api/auth/login' && !location.pathname.endsWith('/login.html')) {
window.location.href = '/login.html';
}
}
const API = {
async get(path) {
const res = await fetch(path);
const data = await res.json();
if (!res.ok) {
redirecionaSeSessaoExpirou(path, res.status);
throw new Error(data.erro || `HTTP ${res.status}`);
}
return data;
},
async send(method, path, body) {
const res = await fetch(path, {
method,
headers: { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body)
});
const data = await res.json();
if (!res.ok) {
redirecionaSeSessaoExpirou(path, res.status);
const error = new Error(data.erro || `HTTP ${res.status}`);
error.data = data;
error.status = res.status;
throw error;
}
return data;
},
post(path, body) { return this.send('POST', path, body); },
put(path, body) { return this.send('PUT', path, body); },
// Acompanha um job via SSE; handlers: {progress, log, done, error}
watchJob(jobId, handlers) {
const source = new EventSource(`/api/jobs/${jobId}/events`);
const close = () => source.close();
source.addEventListener('progress', (e) => handlers.progress?.(JSON.parse(e.data)));
source.addEventListener('log', (e) => handlers.log?.(JSON.parse(e.data)));
source.addEventListener('done', (e) => {
handlers.done?.(JSON.parse(e.data));
close();
});
source.addEventListener('error', (e) => {
if (e.data) {
handlers.error?.(JSON.parse(e.data));
close();
}
// sem e.data = queda de conexão; EventSource tenta reconectar sozinho
});
return close;
}
};
const fmt = new Intl.NumberFormat('pt-BR');
function el(id) { return document.getElementById(id); }
function h(tag, attrs = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(attrs)) {
if (key === 'class') node.className = value;
else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
else if (value !== null && value !== undefined) node.setAttribute(key, value);
}
for (const child of children.flat()) {
if (child === null || child === undefined) continue;
node.append(child.nodeType ? child : document.createTextNode(child));
}
return node;
}
let toastTimer = null;
function toast(message, ms = 3500) {
const box = el('toast');
box.textContent = message;
box.classList.remove('hidden');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => box.classList.add('hidden'), ms);
}
function dataBr(iso) {
if (!iso) return '—';
const d = new Date(iso.includes('T') || iso.includes(' ') ? iso.replace(' ', 'T') + (iso.endsWith('Z') ? '' : 'Z') : iso);
return Number.isNaN(d.getTime()) ? iso : d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}
+137
View File
@@ -0,0 +1,137 @@
/* Shell do aplicativo: login + abas + configurações + usuários. */
(async function init() {
// sessao (o servidor ja bloqueia "/" sem cookie, mas precisamos dos dados do usuario)
let usuarioAtual;
try {
({ user: usuarioAtual } = await API.get('/api/auth/me'));
} catch {
window.location.href = '/login.html';
return;
}
el('usuario-logado').textContent = `${usuarioAtual.username} (${usuarioAtual.role === 'admin' ? 'admin' : 'comercial'})`;
el('btn-usuarios').classList.toggle('hidden', usuarioAtual.role !== 'admin');
el('btn-sair').addEventListener('click', async () => {
await API.post('/api/auth/logout');
window.location.href = '/login.html';
});
// usuarios (somente admin)
async function carregarListaUsuarios() {
const { users } = await API.get('/api/users');
el('lista-usuarios').replaceChildren(...users.map((u) =>
h('div', { class: 'row space-between' },
h('span', {}, u.username),
h('span', { class: 'muted' }, u.role === 'admin' ? 'Administrador' : 'Comercial'))));
}
el('btn-usuarios').addEventListener('click', async () => {
el('modal-usuarios').showModal();
try {
await carregarListaUsuarios();
} catch (error) {
toast(`Erro: ${error.message}`);
}
});
el('btn-fechar-usuarios').addEventListener('click', () => el('modal-usuarios').close());
el('form-novo-usuario').addEventListener('submit', async (event) => {
event.preventDefault();
try {
await API.post('/api/users', {
username: el('novo-usuario-username').value,
password: el('novo-usuario-password').value,
role: el('novo-usuario-role').value
});
el('novo-usuario-username').value = '';
el('novo-usuario-password').value = '';
await carregarListaUsuarios();
toast('Usuário criado');
} catch (error) {
toast(`Erro: ${error.message}`);
}
});
// abas
for (const tab of document.querySelectorAll('.tab')) {
tab.addEventListener('click', () => {
for (const t of document.querySelectorAll('.tab')) {
t.classList.toggle('active', t === tab);
t.setAttribute('aria-selected', t === tab ? 'true' : 'false');
}
for (const panel of document.querySelectorAll('.tab-panel')) {
panel.classList.toggle('active', panel.id === `tab-${tab.dataset.tab}`);
}
if (tab.dataset.tab === 'tratamento') Tratamento.ativar();
});
}
// configurações
el('btn-settings').addEventListener('click', async () => {
const { settings } = await API.get('/api/settings');
el('cfg-pipeline').value = settings['zpro.pipelineId'] || 1;
el('cfg-stage').value = settings['zpro.stageId'] || 1;
el('cfg-responsible').value = settings['zpro.responsibleId'] || 15;
el('cfg-forecast').value = settings['zpro.closingForecastDays'] || 30;
el('modal-settings').showModal();
});
el('btn-salvar-settings').addEventListener('click', async (event) => {
event.preventDefault();
try {
await API.put('/api/settings', {
'zpro.pipelineId': el('cfg-pipeline').value,
'zpro.stageId': el('cfg-stage').value,
'zpro.responsibleId': el('cfg-responsible').value,
'zpro.closingForecastDays': el('cfg-forecast').value
});
el('modal-settings').close();
toast('Configurações salvas');
} catch (error) {
toast(`Erro: ${error.message}`);
}
});
// limpar toda a base (zona de risco)
el('btn-limpar-base').addEventListener('click', () => {
el('reset-base-senha').value = '';
el('modal-settings').close();
el('modal-reset-base').showModal();
});
el('btn-cancelar-reset-base').addEventListener('click', () => {
el('modal-reset-base').close();
});
el('btn-confirmar-reset-base').addEventListener('click', async () => {
const senha = el('reset-base-senha').value;
if (!senha) {
toast('Informe a senha de segurança');
return;
}
try {
await API.post('/api/admin/reset', { senha });
el('modal-reset-base').close();
toast('Base de leads limpa com sucesso — recarregando...');
setTimeout(() => window.location.reload(), 1200);
} catch (error) {
toast(`Erro: ${error.message}`);
}
});
// fecha modais clicando fora
for (const dialog of document.querySelectorAll('dialog')) {
dialog.addEventListener('click', (event) => {
if (event.target === dialog) dialog.close();
});
}
Tratamento.bindEvents();
try {
await Captura.init();
} catch (error) {
toast(`Erro ao carregar: ${error.message}`, 8000);
}
})();
+405
View File
@@ -0,0 +1,405 @@
/* Aba Captura: wizard UF → cidades → nichos → fontes → rodar, com progresso SSE. */
const Captura = (() => {
let ufs = [];
let municipios = []; // da UF selecionada
let segments = [];
let sources = [];
const cidadesEscolhidas = new Set();
const nichosEscolhidos = new Set();
const cnaesAvulsos = new Map(); // codigo -> descricao
let stopWatcher = null;
// ---------- carregamento ----------
async function init() {
const [ufsData, segData, srcData] = await Promise.all([
API.get('/api/meta/ufs'),
API.get('/api/meta/segments'),
API.get('/api/meta/sources')
]);
ufs = ufsData.ufs;
segments = segData.segments;
sources = srcData.sources;
renderUfs();
renderNichos();
renderFontes();
bindEvents();
await onUfChange();
await carregarHistorico();
await retomarJobAtivo();
}
function renderUfs() {
const sel = el('sel-uf');
sel.replaceChildren(...ufs.map((u) =>
h('option', { value: u.uf, selected: u.uf === 'BA' ? '' : null },
`${u.uf} — ${u.nome}${u.extraida ? ' ✓' : ''}`)
));
}
function renderNichos(filtro = '') {
const grid = el('nichos-grid');
const termo = filtro.toLowerCase();
grid.replaceChildren(...segments
.filter((s) => !termo || s.label.toLowerCase().includes(termo))
.map((s) => h('label', {},
h('input', {
type: 'checkbox', value: s.name,
checked: nichosEscolhidos.has(s.name) ? '' : null,
onchange: (e) => {
if (e.target.checked) nichosEscolhidos.add(s.name);
else nichosEscolhidos.delete(s.name);
atualizarContagem();
}
}),
s.label
)));
el('nichos-contagem').textContent = `(${segments.length} disponíveis)`;
}
function atualizarContagem() {
const modo = document.querySelector('input[name="nichos-modo"]:checked').value;
el('nichos-contagem').textContent = modo === 'todos'
? `(${segments.length} disponíveis)`
: `(${nichosEscolhidos.size} de ${segments.length} selecionados)`;
}
function renderFontes() {
const box = el('fontes-lista');
box.replaceChildren(...sources.map((s) => {
const input = h('input', {
type: 'checkbox', value: s.id,
checked: s.id === 'cnpj-base' ? '' : null,
disabled: s.disponivel ? null : ''
});
return h('label', { class: `fonte${s.disponivel ? '' : ' indisponivel'}` },
input,
h('div', {},
h('div', {}, h('strong', {}, s.label), s.recomendada ? ' ⭐' : '', s.gratuita ? '' : ' 💰'),
h('div', { class: 'desc' }, s.descricao + (s.disponivel ? '' : ` — ${s.motivo}`))
)
);
}));
}
// ---------- UF / extração ----------
function ufAtual() {
return ufs.find((u) => u.uf === el('sel-uf').value);
}
async function onUfChange() {
const u = ufAtual();
const status = el('uf-status');
if (u.extraindo) {
status.textContent = '⏳ extraindo base...';
status.className = 'chip warn';
} else if (u.extraida) {
status.textContent = '✓ base CNPJ pronta';
status.className = 'chip ok';
} else {
status.textContent = 'base CNPJ não extraída';
status.className = 'chip warn';
}
el('extracao-aviso').classList.toggle('hidden', u.extraida || u.extraindo);
el('extracao-uf').textContent = `${u.uf} — ${u.nome}`;
cidadesEscolhidas.clear();
renderChips();
const data = await API.get(`/api/meta/municipios?uf=${u.uf}`);
municipios = data.municipios;
}
async function extrairBase() {
const u = ufAtual();
try {
const { jobId } = await API.post('/api/extractions', { uf: u.uf });
toast(`Extração de ${u.uf} iniciada — pode levar até 1 hora`);
acompanharJob(jobId, `Extraindo base CNPJ de ${u.uf}`);
u.extraindo = true;
await onUfChange();
} catch (error) {
toast(`Erro: ${error.message}`);
}
}
// ---------- cidades ----------
function renderChips() {
el('cidades-chips').replaceChildren(...[...cidadesEscolhidas].map((nome) =>
h('span', {
class: 'chip', title: 'remover',
onclick: () => { cidadesEscolhidas.delete(nome); renderChips(); }
}, nome)
));
}
function buscarCidade(termo) {
const box = el('cidades-sugestoes');
if (!termo || termo.length < 2) {
box.replaceChildren();
return;
}
const t = termo.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
const achados = municipios
.filter((m) => m.nome.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').includes(t))
.slice(0, 12);
box.replaceChildren(...achados.map((m) =>
h('button', {
type: 'button',
onclick: () => {
cidadesEscolhidas.add(m.nome);
renderChips();
el('busca-cidade').value = '';
box.replaceChildren();
}
}, m.nome)
));
}
// ---------- CNAE avulso (qualquer atividade da Receita, alem dos 57 nichos) ----------
function renderCnaeChips() {
el('cnae-chips').replaceChildren(...[...cnaesAvulsos].map(([codigo, descricao]) =>
h('span', {
class: 'chip', title: 'remover',
onclick: () => { cnaesAvulsos.delete(codigo); renderCnaeChips(); }
}, descricao)
));
}
let buscaCnaeTimer = null;
function buscarCnae(termo) {
clearTimeout(buscaCnaeTimer);
const box = el('cnae-sugestoes');
if (!termo || termo.trim().length < 2) {
box.replaceChildren();
return;
}
buscaCnaeTimer = setTimeout(async () => {
const { cnaes } = await API.get(`/api/meta/cnaes?q=${encodeURIComponent(termo)}`);
box.replaceChildren(...cnaes.map((c) =>
h('button', {
type: 'button',
onclick: () => {
cnaesAvulsos.set(c.codigo, c.descricao);
renderCnaeChips();
el('busca-cnae').value = '';
box.replaceChildren();
}
}, h('span', {}, c.descricao), h('span', { class: 'cod' }, c.codigo))
));
if (!cnaes.length) {
box.replaceChildren(h('div', { class: 'muted' }, 'Nenhuma atividade encontrada'));
}
}, 250);
}
// ---------- captura ----------
function montarPayload() {
const fontes = [...document.querySelectorAll('#fontes-lista input:checked')].map((i) => i.value);
const cidadesModo = document.querySelector('input[name="cidades-modo"]:checked').value;
const nichosModo = document.querySelector('input[name="nichos-modo"]:checked').value;
const cnaeIds = [...cnaesAvulsos.keys()].map((codigo) => `cnae:${codigo}`);
return {
sources: fontes,
uf: el('sel-uf').value,
cities: cidadesModo === 'todas' ? ['all'] : [...cidadesEscolhidas],
segments: [...(nichosModo === 'todos' ? ['all'] : [...nichosEscolhidos]), ...cnaeIds],
limits: {
maxPerQuery: Number(el('inp-max').value) || 10,
queryLimit: Number(el('inp-query-limit').value) || 0
}
};
}
async function iniciarCaptura() {
const payload = montarPayload();
if (!payload.sources.length) {
toast('Selecione pelo menos uma fonte de busca');
return;
}
if (payload.cities.length === 0) {
toast('Escolha pelo menos uma cidade (ou marque "todas")');
return;
}
if (payload.segments.length === 0) {
toast('Escolha pelo menos um nicho (ou marque "todos")');
return;
}
try {
const { jobId } = await API.post('/api/capture/runs', payload);
acompanharJob(jobId, 'Captura em andamento');
} catch (error) {
if (error.data?.precisaExtracao) {
el('extracao-aviso').classList.remove('hidden');
toast(error.message);
} else {
toast(`Erro: ${error.message}`);
}
}
}
// ---------- progresso ----------
function acompanharJob(jobId, titulo) {
const card = el('progresso-card');
card.classList.remove('hidden');
card.dataset.jobId = jobId;
el('progresso-titulo').textContent = titulo;
el('progresso-msg').textContent = 'iniciando...';
el('progresso-log').textContent = '';
el('progresso-fill').style.width = '3%';
el('progresso-stats').replaceChildren();
el('btn-cancelar').disabled = false;
el('btn-capturar').disabled = true;
if (stopWatcher) stopWatcher();
stopWatcher = API.watchJob(jobId, {
progress(p) {
if (p.message) el('progresso-msg').textContent = p.message;
if (typeof p.pct === 'number') el('progresso-fill').style.width = `${Math.max(3, p.pct)}%`;
if (p.counts) {
el('progresso-fill').style.width = '50%';
el('progresso-stats').replaceChildren(
mini(p.counts.raw, 'encontrados'),
mini(p.counts.new, 'novos'),
mini(p.counts.dup, 'já capturados')
);
}
},
log(l) {
const box = el('progresso-log');
box.textContent += `${l.message}\n`;
box.scrollTop = box.scrollHeight;
},
done(d) {
el('progresso-fill').style.width = '100%';
const s = d.summary || {};
el('progresso-msg').textContent = s.cancelled
? 'Cancelado.'
: s.totalRows !== undefined
? `✅ Base extraída: ${fmt.format(s.totalRows)} empresas (${fmt.format(s.withPhone)} com telefone)`
: `✅ Concluído: ${fmt.format(s.new ?? 0)} leads novos (${fmt.format(s.dup ?? 0)} já capturados antes)`;
finalizar();
},
error(e) {
el('progresso-msg').textContent = `❌ Erro: ${e.message}`;
finalizar();
}
});
function mini(valor, rotulo) {
return h('div', { class: 'mini' }, h('b', {}, fmt.format(valor ?? 0)), h('span', {}, rotulo));
}
async function finalizar() {
el('btn-cancelar').disabled = true;
el('btn-capturar').disabled = false;
await Promise.all([carregarHistorico(), recarregarUfs()]);
window.Tratamento?.invalidar();
}
}
async function recarregarUfs() {
ufs = (await API.get('/api/meta/ufs')).ufs;
const atual = el('sel-uf').value;
renderUfs();
el('sel-uf').value = atual;
await onUfChange();
}
async function cancelarJob() {
const jobId = el('progresso-card').dataset.jobId;
const ativos = (await API.get('/api/jobs/active')).jobs;
const job = ativos.find((j) => j.jobId === jobId);
if (!job) {
toast('Nenhum job ativo para cancelar');
return;
}
const rota = job.type === 'extracao'
? `/api/extractions/${job.meta.extractionId}/cancel`
: `/api/capture/runs/${job.meta.runId}/cancel`;
try {
await API.post(rota, {});
toast('Cancelamento solicitado — aguardando o processo parar...');
} catch (error) {
toast(`Erro: ${error.message}`);
}
}
async function retomarJobAtivo() {
const ativos = (await API.get('/api/jobs/active')).jobs;
if (!ativos.length) return;
const job = ativos[0];
acompanharJob(job.jobId, job.type === 'extracao'
? `Extraindo base CNPJ de ${job.meta.uf}`
: 'Captura em andamento');
}
// ---------- histórico ----------
async function carregarHistorico() {
const { runs } = await API.get('/api/capture/runs?limit=8');
el('btn-ver-historico').textContent = runs.length ? `🕓 Histórico de capturas (${runs.length})` : '🕓 Histórico de capturas';
const box = el('historico-capturas');
if (!runs.length) {
box.replaceChildren(h('div', { class: 'muted' }, 'Nenhuma captura ainda. Configure ao lado e clique em Iniciar.'));
return;
}
const statusLabel = {
done: '✅ concluída', running: '⏳ rodando', pending: '⏳ na fila',
cancelled: '⚪ cancelada', error: '❌ erro'
};
box.replaceChildren(...runs.map((r) => h('div', { class: 'item' },
h('div', {},
h('div', {}, h('strong', {}, `#${r.id} · ${(r.params.sources || []).join(', ')} · ${r.params.uf || ''}`)),
h('div', { class: 'sub' },
`${dataBr(r.created_at)} · ${statusLabel[r.status] || r.status}`,
r.error ? ` · ${r.error.slice(0, 80)}` : '')
),
h('div', { class: 'sub' },
r.status === 'done' ? `${fmt.format(r.new_count)} novos / ${fmt.format(r.dup_count)} repetidos` : '')
)));
}
// ---------- eventos ----------
function bindEvents() {
el('sel-uf').addEventListener('change', onUfChange);
el('btn-extrair').addEventListener('click', extrairBase);
el('btn-capturar').addEventListener('click', iniciarCaptura);
el('btn-cancelar').addEventListener('click', cancelarJob);
el('btn-ver-historico').addEventListener('click', () => el('modal-historico').showModal());
el('btn-fechar-historico').addEventListener('click', () => el('modal-historico').close());
for (const radio of document.querySelectorAll('input[name="cidades-modo"]')) {
radio.addEventListener('change', () => {
el('cidades-picker').classList.toggle('hidden', radio.value !== 'escolher' || !radio.checked);
});
}
for (const radio of document.querySelectorAll('input[name="nichos-modo"]')) {
radio.addEventListener('change', () => {
el('nichos-picker').classList.toggle('hidden', radio.value !== 'escolher' || !radio.checked);
atualizarContagem();
});
}
el('busca-cidade').addEventListener('input', (e) => buscarCidade(e.target.value));
el('busca-nicho').addEventListener('input', (e) => renderNichos(e.target.value));
el('busca-cnae').addEventListener('input', (e) => buscarCnae(e.target.value));
el('btn-nichos-todos').addEventListener('click', () => {
for (const input of document.querySelectorAll('#nichos-grid input')) {
input.checked = true;
nichosEscolhidos.add(input.value);
}
atualizarContagem();
});
el('btn-nichos-nenhum').addEventListener('click', () => {
nichosEscolhidos.clear();
renderNichos(el('busca-nicho').value);
atualizarContagem();
});
}
return { init };
})();
+16
View File
@@ -0,0 +1,16 @@
/* Tela de login: autentica e redireciona para o app. */
el('form-login').addEventListener('submit', async (event) => {
event.preventDefault();
const erroBox = el('login-erro');
erroBox.textContent = '';
try {
await API.post('/api/auth/login', {
username: el('login-username').value,
password: el('login-password').value
});
window.location.href = '/';
} catch (error) {
erroBox.textContent = error.message;
}
});
+629
View File
@@ -0,0 +1,629 @@
/* Aba Tratamento: dashboard, navegador de leads com filtros e exportações. */
const Tratamento = (() => {
let page = 1;
let totalPages = 1;
let carregado = false;
let refreshTimer = null;
const CLASSIFICACAO_LABELS = {
excelente: 'Excelente', bom: 'Bom', medio: 'Médio', baixo: 'Baixo', muito_baixo: 'Muito Baixo'
};
const PRIORIDADE_LABELS = {
1: 'P1 — atacar imediatamente', 2: 'P2 — trabalhar durante a semana',
3: 'P3 — quando não houver prioritários', 4: 'P4 — só em campanhas específicas'
};
function estrelas(n) {
const cheias = Math.max(0, Math.min(5, Number(n) || 0));
return '★'.repeat(cheias) + '☆'.repeat(5 - cheias);
}
// ---------- filtros ----------
function filtroAtual() {
const filtro = {};
for (const input of document.querySelectorAll('#filtros [data-filtro]')) {
const value = input.value.trim();
if (value) filtro[input.dataset.filtro] = value;
}
return filtro;
}
function filtroQuery(extra = {}) {
return new URLSearchParams({ ...filtroAtual(), ...extra }).toString();
}
// Clique nos cards/barras do dashboard: aplica o filtro somando aos ja
// ativos; clicar de novo no mesmo valor remove so aquele filtro.
function toggleFiltro(inputId, valor) {
const input = el(inputId);
const novo = String(valor ?? '');
input.value = input.value === novo ? '' : novo;
atualizar();
}
function descreverFiltro() {
const f = filtroAtual();
const partes = [];
if (f.uf) partes.push(`UF ${f.uf}`);
if (f.cidade) partes.push(f.cidade);
if (f.segmento) partes.push(el('f-segmento').selectedOptions[0]?.textContent || f.segmento);
if (f.classificacao) partes.push(CLASSIFICACAO_LABELS[f.classificacao] || f.classificacao);
if (f.prioridade) partes.push(`P${f.prioridade}`);
if (f.produto) partes.push(`produto: ${f.produto}`);
if (f.interesse) partes.push(f.interesse);
if (f.telefone_valido) partes.push(f.telefone_valido === 'sim' ? 'com WhatsApp' : 'sem WhatsApp');
if (f.website) partes.push(f.website === 'sim' ? 'com website' : 'sem website');
if (f.email) partes.push(f.email === 'sim' ? 'com e-mail' : 'sem e-mail');
if (f.exportado) partes.push(f.exportado === 'nao' ? 'ainda não exportados' : 'já exportados');
if (f.q) partes.push(`busca "${f.q}"`);
return partes.length ? partes.join(' · ') : 'todos os leads';
}
// ---------- carregamento ----------
async function atualizar() {
page = 1;
const [summary, evolutionRes, oportunidadeRes] = await Promise.all([
API.get(`/api/dashboard/summary?${filtroQuery()}`),
API.get(`/api/dashboard/evolution?dias=14&${filtroQuery()}`),
API.get(`/api/dashboard/oportunidade?${filtroQuery()}`)
]);
await Promise.all([carregarTiles(summary), carregarRankings(summary), carregarFunil(summary), carregarTabela()]);
carregarEvolucaoDiaria(evolutionRes.evolution);
carregarMaiorOportunidade(oportunidadeRes.oportunidade);
}
function invalidar() {
carregado = false;
clearTimeout(refreshTimer);
refreshTimer = setTimeout(() => {
if (document.querySelector('#tab-tratamento.active')) ativar();
}, 800);
}
async function ativar() {
if (carregado) return;
carregado = true;
await Promise.all([carregarFacets(), atualizar(), carregarExports()]);
}
async function carregarFacets() {
const facets = await API.get('/api/leads/facets');
const fill = (select, valores, prefixo, formatar = (v) => v) => {
const atual = select.value;
const primeira = select.options[0];
select.replaceChildren(primeira, ...valores.map((item) =>
h('option', { value: item.value }, `${formatar(item.value)} (${fmt.format(item.total)})`)
));
select.value = atual;
};
fill(el('f-uf'), facets.ufs);
fill(el('f-interesse'), facets.interesses);
fill(el('f-produto'), facets.produtos);
const segSelect = el('f-segmento');
const atual = segSelect.value;
segSelect.replaceChildren(segSelect.options[0], ...facets.segmentos.map((s) =>
h('option', { value: s.value }, `${s.value.replace(/_/g, ' ')} (${fmt.format(s.total)})`)
));
segSelect.value = atual;
el('dl-cidades').replaceChildren(...facets.cidades.map((c) => h('option', { value: c.value })));
}
async function salvarMetaDiaria(valor) {
const meta = Math.max(1, Number(valor) || 100);
await API.put('/api/settings', { meta_diaria: meta });
const summary = await API.get(`/api/dashboard/summary?${filtroQuery()}`);
carregarTiles(summary);
}
async function carregarTiles(s) {
const pct = (n) => s.total ? ` (${((n / s.total) * 100).toFixed(1)}%)` : '';
el('stat-tiles').replaceChildren(
tile(s.total, 'Leads no filtro', ''),
tile(s.com_whatsapp, 'Com WhatsApp', pct(s.com_whatsapp), 't-good'),
tile(s.p1, '🎯 Potencial Comercial Imediato', `${s.potencial_pct}% da base — atacar agora`, 't-good'),
tile(s.p4, '📦 P4 — campanhas específicas', pct(s.p4))
);
el('stat-tiles').append(
cardCobertura(s),
cardPrioridades(s),
cardMeta(s)
);
function tile(valor, rotulo, detalhe, cls = '') {
return h('div', { class: `tile ${cls}` },
h('div', { class: 'valor' }, fmt.format(valor)),
h('div', { class: 'rotulo' }, rotulo),
h('div', { class: 'detalhe' }, detalhe)
);
}
function cardCobertura(s) {
const cidadeAtiva = filtroAtual().cidade;
const titulo = cidadeAtiva ? `Cobertura em ${cidadeAtiva}` : 'Base Comercial — cobertura';
return h('div', { class: 'tile tile-wide' },
h('div', { class: 'rotulo' }, titulo),
h('div', { class: 'progress-bar' },
h('div', { class: 'progress-fill', style: `width:${s.cobertura_pct}%` })),
h('div', { class: 'detalhe' },
`${s.cobertura_pct}% trabalhada · ${fmt.format(s.exportados)} exportadas · ${fmt.format(s.disponiveis)} disponíveis`)
);
}
function cardPrioridades(s) {
const ativa = filtroAtual().prioridade;
const linhas = [
['P1', s.p1, s.p1_pct], ['P2', s.p2, s.p2_pct], ['P3', s.p3, s.p3_pct], ['P4', s.p4, s.p4_pct]
];
return h('div', { class: 'tile tile-wide' },
h('div', { class: 'rotulo' }, 'Distribuição por prioridade'),
h('div', { class: 'ranking', style: 'margin-top:6px' }, ...linhas.map(([label, total, p], i) =>
h('div', {
class: `rank-row${ativa === String(i + 1) ? ' ativo' : ''}`,
title: `${label}: ${fmt.format(total)} leads — clique para filtrar`,
onclick: () => toggleFiltro('f-prioridade', i + 1)
},
h('div', { class: 'rank-label' }, label),
h('div', { class: 'rank-track' }, h('div', { class: 'rank-fill', style: `width:${Math.max(1.5, p)}%` })),
h('div', { class: 'rank-value' }, `${p}%`)
)))
);
}
function cardMeta(s) {
return h('div', { class: 'tile tile-wide' },
h('div', { class: 'row space-between' },
h('div', { class: 'rotulo' }, '🎯 Meta diária'),
h('input', {
type: 'number', min: '1', value: String(s.meta_diaria), class: 'meta-input',
onchange: (e) => salvarMetaDiaria(e.target.value)
})
),
h('div', { class: 'progress-bar' },
h('div', { class: 'progress-fill', style: `width:${Math.min(100, s.meta_pct)}%` })),
h('div', { class: 'detalhe' },
`${fmt.format(s.hoje_exportados)} de ${fmt.format(s.meta_diaria)} hoje (${s.meta_pct}%) · ~${fmt.format(s.dias_estimados)} dias úteis restantes no ritmo atual`)
);
}
}
async function carregarRankings(summary) {
const cidadeAtiva = filtroAtual().cidade;
el('rank-produtos-titulo').textContent = cidadeAtiva ? `Produtos recomendados em ${cidadeAtiva}` : 'Top produto recomendado';
const [cidades, segmentos, produtos] = await Promise.all([
API.get(`/api/dashboard/rankings?by=cidade&limit=10&${filtroQuery()}`),
API.get(`/api/dashboard/rankings?by=segmento&limit=10&${filtroQuery()}`),
API.get(`/api/dashboard/rankings?by=produto&limit=10&${filtroQuery()}`)
]);
const f = filtroAtual();
const segmentoValuePorLabel = (label) => {
const opts = [...el('f-segmento').options];
const porValor = opts.find((o) => o.value && o.value.replace(/_/g, ' ').toLowerCase() === label.toLowerCase());
const porTexto = opts.find((o) => o.textContent.toLowerCase().startsWith(label.toLowerCase()));
return (porValor || porTexto)?.value || '';
};
renderRanking(el('rank-cidades'), cidades.ranking,
(label) => toggleFiltro('f-cidade', label),
null,
(label) => f.cidade === label);
renderRanking(el('rank-segmentos'), segmentos.ranking,
(label) => toggleFiltro('f-segmento', segmentoValuePorLabel(label)),
null,
(label) => !!f.segmento && f.segmento === segmentoValuePorLabel(label));
renderRanking(el('rank-produtos'), produtos.ranking,
(label) => toggleFiltro('f-produto', label),
summary.total,
(label) => f.produto === label);
carregarOportunidadesDoDia(produtos.ranking, summary.total);
}
function carregarOportunidadesDoDia(produtosRanking, totalGeral) {
const top3 = produtosRanking.slice(0, 3);
if (!top3.length) {
el('card-oportunidades-dia').replaceChildren(
h('h2', {}, '🔥 Oportunidades do Dia'),
h('div', { class: 'muted' }, 'Sem dados para este filtro.')
);
return;
}
const produtoAtivo = filtroAtual().produto;
el('card-oportunidades-dia').replaceChildren(
h('h2', {}, '🔥 Oportunidades do Dia'),
h('div', { class: 'ranking', style: 'margin-top:6px' }, ...top3.map((r) => {
const p = totalGeral ? Math.round((r.total / totalGeral) * 100) : 0;
return h('div', {
class: `rank-row${produtoAtivo === r.label ? ' ativo' : ''}`,
title: `${r.label}: ${fmt.format(r.total)} leads — clique para filtrar`,
onclick: () => toggleFiltro('f-produto', r.label)
},
h('div', { class: 'rank-label' }, r.label),
h('div', { class: 'rank-track' }, h('div', { class: 'rank-fill', style: `width:${Math.max(1.5, p)}%` })),
h('div', { class: 'rank-value' }, `${p}%`)
);
}))
);
}
function dataBrCurta(diaIso) {
const [, mes, dia] = diaIso.split('-');
return `${dia}/${mes}`;
}
function carregarEvolucaoDiaria(evolution) {
if (!evolution.length) {
el('card-evolucao-diaria').replaceChildren(
h('h2', {}, '📈 Evolução Diária'),
h('div', { class: 'muted' }, 'Nenhuma exportação registrada ainda.')
);
return;
}
const max = Math.max(...evolution.map((d) => d.total));
el('card-evolucao-diaria').replaceChildren(
h('h2', {}, '📈 Evolução Diária'),
h('div', { class: 'muted', style: 'margin:2px 0 8px' }, 'Exportações por dia — única atividade com data registrada hoje.'),
h('div', { class: 'ranking' }, ...evolution.map((d) => h('div', { class: 'rank-row nao-clicavel' },
h('div', { class: 'rank-label' }, dataBrCurta(d.dia)),
h('div', { class: 'rank-track' }, h('div', { class: 'rank-fill', style: `width:${Math.max(1.5, (d.total / max) * 100)}%` })),
h('div', { class: 'rank-value' }, fmt.format(d.total))
)))
);
}
function carregarMaiorOportunidade(oportunidade) {
if (!oportunidade) {
el('card-maior-oportunidade').replaceChildren(
h('h2', {}, '🏆 Maior Oportunidade'),
h('div', { class: 'muted' }, 'Sem dados suficientes para este filtro.')
);
return;
}
const f = filtroAtual();
const jaAplicado = f.cidade === oportunidade.cidade && f.produto === oportunidade.produto;
el('card-maior-oportunidade').replaceChildren(
h('h2', {}, '🏆 Maior Oportunidade'),
h('div', {
class: `row space-between oportunidade-clicavel${jaAplicado ? ' ativo' : ''}`,
style: 'margin-top:6px',
title: jaAplicado ? 'Clique para remover o filtro cidade + produto' : 'Clique para filtrar por esta cidade + produto',
onclick: () => {
el('f-cidade').value = jaAplicado ? '' : oportunidade.cidade;
el('f-produto').value = jaAplicado ? '' : oportunidade.produto;
atualizar();
}
},
h('div', {}, h('div', { class: 'rotulo' }, 'Cidade'), h('div', { class: 'valor', style: 'font-size:20px' }, oportunidade.cidade)),
h('div', {}, h('div', { class: 'rotulo' }, 'Produto'), h('div', { class: 'valor', style: 'font-size:20px' }, oportunidade.produto)),
h('div', {}, h('div', { class: 'rotulo' }, 'Empresas'), h('div', { class: 'valor', style: 'font-size:20px' }, fmt.format(oportunidade.total)))
)
);
}
function renderRanking(box, ranking, onClick, totalGeral, isAtivo = () => false) {
if (!ranking.length) {
box.replaceChildren(h('div', { class: 'muted' }, 'Sem dados para este filtro.'));
return;
}
const max = ranking[0].total;
box.replaceChildren(...ranking.map((r) => {
const pctGeral = totalGeral ? ` · ${Math.round((r.total / totalGeral) * 100)}%` : '';
const ativo = isAtivo(r.label);
return h('div', {
class: `rank-row${ativo ? ' ativo' : ''}`,
title: `${r.label}: ${fmt.format(r.total)} leads (${fmt.format(r.p1)} prioridade 1) — ${ativo ? 'clique para remover o filtro' : 'clique para filtrar'}`,
onclick: () => onClick(r.label)
},
h('div', { class: 'rank-label' }, r.label),
h('div', { class: 'rank-track' },
h('div', { class: 'rank-fill', style: `width:${Math.max(1.5, (r.total / max) * 100)}%` })),
h('div', { class: 'rank-value' }, `${fmt.format(r.total)}${pctGeral}`)
);
}));
}
const FUNIL_ETAPAS = [
{ key: 'total', label: 'Leads capturados' },
{ key: 'disponiveis', label: 'Leads disponíveis' },
{ key: 'exportados', label: 'Leads exportados' },
{ key: null, label: 'Empresas contatadas' },
{ key: null, label: 'Empresas interessadas' },
{ key: null, label: 'Propostas enviadas' },
{ key: null, label: 'Clientes convertidos' }
];
function carregarFunil(s) {
const base = s.total || 1;
el('card-funil').replaceChildren(
h('h2', {}, 'Evolução Comercial'),
h('div', { class: 'funil' }, ...FUNIL_ETAPAS.map((etapa) => {
const pendente = etapa.key === null;
const valor = pendente ? null : s[etapa.key];
const largura = pendente ? 0 : Math.max(1.5, (valor / base) * 100);
return h('div', { class: `funil-etapa${pendente ? ' pendente' : ''}`,
title: pendente ? 'Aguardando integração com CRM' : '' },
h('div', { class: 'funil-label' }, etapa.label),
h('div', { class: 'funil-barra' }, h('div', { class: 'funil-fill', style: `width:${largura}%` })),
h('div', { class: 'funil-valor' }, pendente ? '—' : fmt.format(valor))
);
}))
);
}
async function carregarTabela() {
const data = await API.get(`/api/leads?${filtroQuery({ page, pageSize: 50 })}`);
totalPages = Math.max(1, Math.ceil(data.total / data.pageSize));
el('leads-total').textContent = `— ${fmt.format(data.total)} encontrados`;
el('pg-info').textContent = `página ${data.page} de ${fmt.format(totalPages)}`;
el('pg-prev').disabled = page <= 1;
el('pg-next').disabled = page >= totalPages;
const tbody = document.querySelector('#tabela-leads tbody');
if (!data.rows.length) {
tbody.replaceChildren(h('tr', {}, h('td', { colspan: '9', class: 'muted' }, 'Nenhum lead com este filtro.')));
return;
}
tbody.replaceChildren(...data.rows.map((lead) => h('tr', { onclick: () => abrirLead(lead.id) },
h('td', { class: 'empresa-cell', title: lead.legal_name || lead.empresa }, lead.empresa),
h('td', {}, lead.whatsapp || '—'),
h('td', {}, lead.cidade),
h('td', {}, lead.segmento_label || lead.segmento),
h('td', {}, h('span', { class: `badge prioridade-${lead.prioridade}` }, `P${lead.prioridade}`)),
h('td', { class: 'num' }, String(lead.score)),
h('td', {}, h('span', { class: `badge ${lead.classificacao}` }, CLASSIFICACAO_LABELS[lead.classificacao] || lead.classificacao)),
h('td', { class: 'produto-cell' }, produtoCell(lead.produto_principal, lead.afinidade)),
h('td', {}, lead.exported_at ? '📤 sim' : '—')
)));
}
const AFINIDADE_TABELA_LABELS = { alta: 'Alta aderência', media: 'Média aderência', baixa: 'Baixa aderência' };
function produtoCell(produto, afinidade) {
if (!produto) return '—';
const label = AFINIDADE_TABELA_LABELS[afinidade];
return label ? `${produto} · ${label}` : produto;
}
const OBSERVACAO_POR_PRIORIDADE = {
1: 'Empresa apta para abordagem imediata.',
2: 'Aguardar a janela de trabalho desta semana.',
3: 'Abordar quando não houver leads de prioridade mais alta.',
4: 'Reservar para campanhas específicas — baixa prioridade comercial.'
};
const AFINIDADE_LABELS = { alta: 'nicho de alta aderência', media: 'nicho de média aderência', baixa: 'nicho de baixa aderência' };
function montarResumoComercial(lead) {
const potencial = Math.max(1, Math.min(5, Math.round((lead.score_comercial || 0) / 20)));
const pontosFortes = [];
if (lead.telefone_valido) pontosFortes.push('WhatsApp válido');
if (lead.cnpj_valido) pontosFortes.push('CNPJ válido');
if (lead.website) pontosFortes.push('Website');
if (lead.email) pontosFortes.push('E-mail cadastrado');
if (lead.afinidade) pontosFortes.push(AFINIDADE_LABELS[lead.afinidade] || 'nicho identificado');
return h('div', { class: 'resumo-comercial' },
h('h3', {}, 'Resumo comercial'),
h('div', { class: 'row space-between' },
h('span', { class: 'estrelas', title: `Potencial comercial: ${potencial}/5` }, estrelas(potencial)),
h('span', { class: `badge prioridade-${lead.prioridade}` }, PRIORIDADE_LABELS[lead.prioridade] || `P${lead.prioridade}`)
),
lead.produtos && lead.produtos.length
? h('div', {}, h('div', { class: 'muted', style: 'margin:8px 0 4px' }, 'Produtos recomendados'),
...lead.produtos.map((p) => h('div', {}, h('span', { class: 'estrelas' }, estrelas(p.estrelas)), ` ${p.nome}`)))
: h('div', { class: 'muted', style: 'margin-top:8px' }, 'Nenhum produto sugerido para este nicho.'),
pontosFortes.length
? h('ul', { class: 'pontos-fortes', style: 'margin-top:10px' }, ...pontosFortes.map((p) => h('li', {}, `✓ ${p}`)))
: null,
h('p', { class: 'muted', style: 'margin:10px 0 0' }, OBSERVACAO_POR_PRIORIDADE[lead.prioridade] || '')
);
}
function montarScoreBreakdown(lead) {
const nichoPontos = lead.afinidade === 'alta' ? '+40' : lead.afinidade === 'baixa' ? '+20' : '+30';
const qualidade = [
[lead.telefone_valido, 'WhatsApp válido', '+30'],
[lead.cnpj_valido, 'CNPJ válido', '+20'],
[lead.empresa_valida, 'Empresa válida', '+20'],
[!!lead.cidade, 'Cidade identificada', '+5'],
[!!lead.segmento, 'Nicho identificado', '+10'],
[!!lead.cnae, 'CNAE identificado', '+10'],
[!!lead.website, 'Website informado', '+5']
];
const comercial = [
[true, `Nicho ${AFINIDADE_TABELA_LABELS[lead.afinidade] || 'de aderência não identificada'}`, nichoPontos],
[!!lead.website, 'Website informado', '+15'],
[!!lead.email, 'E-mail informado', '+10'],
[lead.telefone_valido, 'WhatsApp válido', '+15'],
[lead.cnpj_valido, 'CNPJ válido', '+20']
];
const bloco = (itens, titulo, valorTotal) => h('div', {},
h('div', { class: 'row space-between', style: 'margin-top:10px' },
h('strong', {}, titulo), h('span', {}, String(valorTotal))),
h('ul', { class: 'score-breakdown' }, ...itens.map(([ok, label, pontos]) =>
h('li', { class: ok ? 'ok' : 'nok' }, `${ok ? '✓' : '✗'} ${label} (${pontos})`)))
);
return h('div', { class: 'score-breakdown-wrap' },
bloco(qualidade, 'Score Qualidade', lead.score_qualidade),
bloco(comercial, 'Score Comercial', lead.score_comercial)
);
}
async function abrirLead(id) {
const lead = await API.get(`/api/leads/${id}`);
const linha = (dt, dd) => [h('dt', {}, dt), h('dd', {}, dd || '—')];
el('lead-detalhe').replaceChildren(
h('h2', {}, lead.empresa),
montarResumoComercial(lead),
montarScoreBreakdown(lead),
h('dl', { class: 'detalhe-grid', style: 'margin-top:14px' },
linha('Razão social', lead.legal_name),
linha('WhatsApp', lead.whatsapp),
linha('Cidade/UF', `${lead.cidade}/${lead.uf}`),
linha('Endereço', lead.endereco),
linha('Nicho', lead.segmento_label || lead.segmento),
linha('Interesse', lead.interesse),
linha('CNPJ', lead.cnpj),
linha('CNAE', lead.cnae),
linha('Score geral', `${lead.score} (${CLASSIFICACAO_LABELS[lead.classificacao] || lead.classificacao})`),
linha('Dores', (lead.pains || []).join(', ')),
linha('Origem', lead.origem),
linha('Capturado em', dataBr(lead.captured_at || lead.created_at)),
linha('Exportado em', lead.exported_at ? dataBr(lead.exported_at) : 'ainda não'),
linha('Exportações', lead.exports.length
? lead.exports.map((e) => `#${e.id} ${e.tipo}`).join(', ')
: 'nenhuma')
),
h('div', { class: 'row space-between', style: 'margin-top:14px' },
h('button', { class: 'btn-ghost', onclick: () => el('modal-lead').close() }, 'Fechar')
)
);
el('modal-lead').showModal();
}
// ---------- exportação ----------
const EXPORT_ATALHOS = [
{ label: 'Só P1', set: () => { el('f-prioridade').value = '1'; } },
{ label: 'Só ERP', set: () => { el('f-produto').value = 'ERP'; } },
{ label: 'Só G-Chat', set: () => { el('f-produto').value = 'G-Chat'; } },
{ label: 'Só Sistema de Ponto', set: () => { el('f-produto').value = 'Sistema de Ponto'; } },
{ label: 'Não exportados', set: () => { el('f-exportado').value = 'nao'; } }
];
async function atualizarRecapExport() {
const { total } = await API.get(`/api/dashboard/summary?${filtroQuery()}`);
el('export-recap').textContent = `${fmt.format(total)} leads · ${descreverFiltro()}`;
return total;
}
function renderAtalhosExport() {
el('export-atalhos').replaceChildren(...EXPORT_ATALHOS.map((atalho) =>
h('button', {
type: 'button', class: 'chip', onclick: async () => {
atalho.set();
await atualizar();
await atualizarRecapExport();
}
}, atalho.label)));
}
async function abrirModalExport() {
const total = await atualizarRecapExport();
if (!total) {
toast('Nenhum lead com este filtro — ajuste os filtros antes de exportar');
return;
}
renderAtalhosExport();
const { settings } = await API.get('/api/settings');
el('zp-pipeline').value = settings['zpro.pipelineId'] || 1;
el('zp-stage').value = settings['zpro.stageId'] || 1;
el('zp-responsible').value = settings['zpro.responsibleId'] || 15;
el('modal-export').showModal();
}
async function confirmarExport(event) {
event.preventDefault();
const tipo = document.querySelector('input[name="export-tipo"]:checked').value;
const body = {
tipo,
filtro: filtroAtual(),
params: {
marcarExportado: el('export-marcar').checked,
pipelineId: Number(el('zp-pipeline').value) || undefined,
stageId: Number(el('zp-stage').value) || undefined,
responsibleId: Number(el('zp-responsible').value) || undefined,
mensagem: tipo === 'zpro-bulk' ? el('export-mensagem').value : undefined
}
};
try {
const { jobId, totalEstimado } = await API.post('/api/exports', body);
el('modal-export').close();
toast(`Gerando arquivos para ${fmt.format(totalEstimado)} leads...`);
API.watchJob(jobId, {
done() {
toast('✅ Exportação pronta! Baixe os arquivos na lista abaixo.');
carregarExports();
atualizar();
},
error(e) {
toast(`❌ Erro na exportação: ${e.message}`);
carregarExports();
}
});
} catch (error) {
toast(`Erro: ${error.message}`);
}
}
async function carregarExports() {
const { exports } = await API.get('/api/exports?limit=12');
const box = el('historico-exports');
if (!exports.length) {
box.replaceChildren(h('div', { class: 'muted' }, 'Nenhuma exportação gerada ainda.'));
return;
}
const tipoLabel = {
excel: '📊 Planilha', 'zpro-oportunidades': '🗂️ Z-PRO Oportunidades',
'zpro-bulk': '📨 Z-PRO Disparo em massa', legado: '📦 Importação antiga (Z-PRO)'
};
box.replaceChildren(...exports.map((e) => h('div', { class: 'item' },
h('div', {},
h('div', {}, h('strong', {}, `#${e.id} · ${tipoLabel[e.tipo] || e.tipo}`),
` · ${fmt.format(e.total_leads)} leads`),
h('div', { class: 'sub' }, `${dataBr(e.created_at)} · ${e.status}${e.error ? ` · ${e.error.slice(0, 60)}` : ''}`)
),
h('div', { class: 'row' }, ...(e.status === 'done' && e.tipo !== 'legado'
? e.arquivos.map((nome) =>
h('a', { class: 'btn-ghost', href: `/api/exports/${e.id}/download?arquivo=${encodeURIComponent(nome)}` },
`⬇ ${nome.split('.').pop().toUpperCase()}`))
: []))
)));
}
// ---------- eventos ----------
function bindEvents() {
let debounce = null;
for (const input of document.querySelectorAll('#filtros [data-filtro]')) {
input.addEventListener(input.tagName === 'SELECT' ? 'change' : 'input', () => {
clearTimeout(debounce);
debounce = setTimeout(atualizar, input.tagName === 'SELECT' ? 0 : 350);
});
}
el('btn-limpar-filtros').addEventListener('click', () => {
for (const input of document.querySelectorAll('#filtros [data-filtro]')) input.value = '';
atualizar();
});
el('pg-prev').addEventListener('click', () => { page -= 1; carregarTabela(); });
el('pg-next').addEventListener('click', () => { page += 1; carregarTabela(); });
el('btn-exportar').addEventListener('click', abrirModalExport);
el('form-export').addEventListener('submit', confirmarExport);
for (const radio of document.querySelectorAll('input[name="export-tipo"]')) {
radio.addEventListener('change', () => {
el('export-mensagem-wrap').classList.toggle('hidden', radio.value !== 'zpro-bulk');
el('export-zpro-params').classList.toggle('hidden', radio.value === 'excel');
});
}
el('export-zpro-params').classList.add('hidden');
}
return { ativar, invalidar, bindEvents };
})();
window.Tratamento = Tratamento;
+33
View File
@@ -0,0 +1,33 @@
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GTI Máquina Comercial — Login</title>
<link rel="stylesheet" href="/css/app.css">
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🎯</text></svg>">
</head>
<body class="login-body">
<main class="login-wrap">
<form class="card login-card" id="form-login">
<div class="brand login-brand">
<span class="brand-mark">GTI</span>
<span class="brand-name">Máquina Comercial</span>
</div>
<div class="field">
<label>Usuário <input type="text" id="login-username" autocomplete="username" required></label>
</div>
<div class="field">
<label>Senha <input type="password" id="login-password" autocomplete="current-password" required></label>
</div>
<p class="muted login-erro" id="login-erro"></p>
<button class="btn btn-primary btn-lg" type="submit">Entrar</button>
</form>
</main>
<div id="toast" class="toast hidden"></div>
<script src="/js/api.js"></script>
<script src="/js/login.js"></script>
</body>
</html>