Carry over pre-existing WABA outreach automation WIP
This work already existed uncommitted in the main working tree (not authored by this branch) and is required as a runtime dependency for the campaign outreach port (zpro-client, templates, outreach routes/UI). Copied in as-is, untouched, so this feature branch has a working baseline; the original uncommitted state in the main checkout is left exactly as it was.
This commit is contained in:
+13
-2
@@ -15,6 +15,17 @@
|
|||||||
# Senha pedida para confirmar a limpeza total da base (Configuracoes > Zona de risco)
|
# Senha pedida para confirmar a limpeza total da base (Configuracoes > Zona de risco)
|
||||||
#GTI_RESET_PASSWORD=troque-esta-senha
|
#GTI_RESET_PASSWORD=troque-esta-senha
|
||||||
|
|
||||||
|
# Credenciais da API externa do Z-PRO (Admin > API no painel do Z-PRO), usadas
|
||||||
|
# pela automacao de envio WhatsApp. Normalmente configuradas direto na tela
|
||||||
|
# (Configuracoes > Credenciais Z-PRO) — essas variaveis aqui sao so um
|
||||||
|
# fallback (util em deploy via Docker/Proxmox) e so valem se os campos da
|
||||||
|
# tela estiverem vazios. Sem credenciais em nenhum dos dois lugares a
|
||||||
|
# automacao fica sem efeito mesmo com outreach.ativo=true.
|
||||||
|
#ZPRO_BASE_URL=seu-dominio-zpro.com.br
|
||||||
|
#ZPRO_API_ID=
|
||||||
|
#ZPRO_BEARER_TOKEN=
|
||||||
|
#ZPRO_WHATSAPP_ID=
|
||||||
|
|
||||||
# Endpoints das fontes gratuitas (padroes ja funcionam; mude so se precisar)
|
# Endpoints das fontes gratuitas (padroes ja funcionam; mude so se precisar)
|
||||||
#OVERPASS_API_URL=https://overpass-api.de/api/interpreter,https://overpass.kumi.systems/api/interpreter
|
#OVERPASS_API_URL=https://overpass-api.de/api/interpreter,https://overpass.kumi.systems/api/interpreter
|
||||||
#NOMINATIM_API_URL=https://nominatim.openstreetmap.org/search
|
#NOMINATIM_API_URL=https://nominatim.openstreetmap.org/search
|
||||||
@@ -23,5 +34,5 @@
|
|||||||
|
|
||||||
# Ritmo das consultas ao OpenStreetMap (ms)
|
# Ritmo das consultas ao OpenStreetMap (ms)
|
||||||
#OVERPASS_REQUEST_DELAY_MS=5000
|
#OVERPASS_REQUEST_DELAY_MS=5000
|
||||||
#OVERPASS_TIMEOUT_MS=45000
|
#OVERPASS_TIMEOUT_MS=15000
|
||||||
#OVERPASS_TEXT_SEARCH=true
|
#OVERPASS_TEXT_SEARCH=false
|
||||||
|
|||||||
@@ -1,89 +1,192 @@
|
|||||||
# GTI Máquina Comercial
|
# GTI Maquina Comercial
|
||||||
|
|
||||||
Aplicativo local do Grupo GTI para **capturar** e **tratar** leads B2B em qualquer
|
Aplicativo local do Grupo GTI para capturar, qualificar, tratar e acionar leads B2B via WhatsApp. O sistema roda no computador do usuario, usa SQLite como banco local e integra com Z-PRO/GChat para envio manual ou automatico.
|
||||||
estado/cidade do Brasil, com foco na base oficial de CNPJs da Receita Federal.
|
|
||||||
|
|
||||||
## Como usar (dia a dia)
|
URL local padrao: `http://127.0.0.1:3900`
|
||||||
|
|
||||||
1. Dê dois cliques em **`GTI-Comercial.exe`** (ou em `INICIAR-GTI.bat`).
|
Login inicial: `admin` / `admin`
|
||||||
2. O navegador abre em `http://127.0.0.1:3900` com duas abas:
|
|
||||||
- **📡 Capturar Leads** — escolha estado, cidades, nichos e fontes e rode a captura
|
|
||||||
com progresso ao vivo. Se a base CNPJ do estado ainda não existe, o botão
|
|
||||||
"Extrair base agora" prepara tudo (~40–60 min, uma única vez por estado).
|
|
||||||
- **📊 Tratar Leads** — dashboard com totais e rankings por cidade/nicho, navegador
|
|
||||||
de leads com filtros (qualidade, WhatsApp, exportado...) e o botão
|
|
||||||
**Gerar relatório / exportação** que produz os arquivos para envio.
|
|
||||||
|
|
||||||
Tudo roda somente neste computador (porta local 127.0.0.1). Nenhum dado sai da máquina,
|
## Uso Diario
|
||||||
exceto as consultas às fontes públicas durante a captura.
|
|
||||||
|
|
||||||
## Exportações disponíveis
|
1. Abra `GTI-Comercial.exe` ou `INICIAR-GTI.bat`.
|
||||||
|
2. Acesse `http://127.0.0.1:3900` e faca login.
|
||||||
|
3. Use a aba `Capturar Leads` para escolher UF, cidades, nichos e fontes.
|
||||||
|
4. Use a aba `Tratar Leads` para filtrar, priorizar, abrir detalhes e exportar leads.
|
||||||
|
5. Use o botao de WhatsApp na primeira coluna da tabela para iniciar uma mensagem para um lead especifico.
|
||||||
|
6. Use `Configuracoes` para ajustar Z-PRO, templates WABA, limites de envio, usuarios e exportacoes.
|
||||||
|
|
||||||
| Tipo | Para quê |
|
## Principais Recursos
|
||||||
|
|
||||||
|
- Captura de leads B2B por UF, cidade e nicho.
|
||||||
|
- Base CNPJ da Receita Federal como fonte principal.
|
||||||
|
- Fontes complementares: OpenStreetMap/Overpass, Nominatim, Wikidata, BrasilAPI e Google Places.
|
||||||
|
- Deduplicacao por CNPJ, telefone/WhatsApp ou empresa+cidade.
|
||||||
|
- Scores de qualidade e potencial comercial.
|
||||||
|
- Dashboard com totais, rankings, funil e maior oportunidade.
|
||||||
|
- Tabela de tratamento com filtros, paginação e detalhe completo do lead.
|
||||||
|
- Acao rapida de WhatsApp por lead, fixa na primeira coluna da tabela.
|
||||||
|
- Envio manual por Z-PRO para numero especifico.
|
||||||
|
- Envio oficial por template WABA aprovado.
|
||||||
|
- Sincronizacao de templates WABA do GChat.
|
||||||
|
- Pre-visualizacao de templates com variaveis resolvidas por lead.
|
||||||
|
- Automacao de envio por produto recomendado, com limite diario.
|
||||||
|
- Exportacoes para Excel/CSV, oportunidades Z-PRO e disparo em massa.
|
||||||
|
- Login local com usuarios `admin` e `comercial`.
|
||||||
|
|
||||||
|
## Fluxo Comercial
|
||||||
|
|
||||||
|
1. Capture ou importe a base de leads.
|
||||||
|
2. Filtre por cidade, nicho, qualidade, WhatsApp, prioridade ou status de exportacao.
|
||||||
|
3. Revise o lead na tabela ou no modal de detalhes.
|
||||||
|
4. Clique no botao de WhatsApp do lead para abrir o envio manual com o numero preenchido.
|
||||||
|
5. Escolha texto livre ou template oficial.
|
||||||
|
6. Se usar template, selecione o modelo salvo e confira a pre-visualizacao.
|
||||||
|
7. Envie pelo Z-PRO e acompanhe o log de envios.
|
||||||
|
|
||||||
|
Ao abrir o envio manual a partir de um lead, o app busca os dados completos desse cliente. Variaveis como `{{cnpj}}`, `{{empresa}}`, `{{businessName}}`, `{{produto}}`, `{{cidade}}`, `{{uf}}`, `{{segmento}}`, `{{whatsapp}}` e `{{email}}` sao preenchidas com os dados reais do lead na pre-visualizacao e no envio.
|
||||||
|
|
||||||
|
## WhatsApp, Z-PRO e GChat
|
||||||
|
|
||||||
|
O app suporta dois tipos de envio:
|
||||||
|
|
||||||
|
| Canal | Uso | Observacao |
|
||||||
|
|---|---|---|
|
||||||
|
| Nao oficial/texto livre | Mensagem manual simples | Usa endpoint externo do Z-PRO para enviar texto |
|
||||||
|
| Oficial/template WABA | Mensagem com template aprovado | Usa template Meta/WABA via Z-PRO |
|
||||||
|
|
||||||
|
Configuracoes importantes ficam em `Configuracoes`:
|
||||||
|
|
||||||
|
- Base URL Z-PRO.
|
||||||
|
- API ID Z-PRO.
|
||||||
|
- Token/Bearer token.
|
||||||
|
- Rota do template (`template`, `templateBody` ou equivalente configurado).
|
||||||
|
- URL de templates do GChat.
|
||||||
|
- Token GChat opcional para sincronizar modelos.
|
||||||
|
- Limite diario de envios.
|
||||||
|
- Templates automaticos por produto.
|
||||||
|
|
||||||
|
O seletor de templates WABA permite carregar modelos sincronizados do GChat. O sistema identifica variaveis posicionais como `{{1}}`, `{{2}}`, `{{3}}` no corpo do template e mostra os campos necessarios.
|
||||||
|
|
||||||
|
## Variaveis Suportadas
|
||||||
|
|
||||||
|
As mensagens e templates podem usar variaveis internas da Maquina Comercial/GChat:
|
||||||
|
|
||||||
|
| Variavel | Valor esperado |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 📊 Planilha (CSV + Excel) | Lista completa com score — números como texto, sem notação científica |
|
| `{{name}}` | Nome do contato quando existir; fallback para empresa |
|
||||||
| 🗂️ Z-PRO Oportunidades (JSONL) | Um payload `createOpportunity` por linha, pronto para importar |
|
| `{{empresa}}` | Nome da empresa |
|
||||||
| 📨 Z-PRO Disparo em massa (CSV) | `dataInput` para `BulkSendMessageWithVariable` + instruções |
|
| `{{businessName}}` | Nome da empresa no padrao GChat |
|
||||||
|
| `{{firstName}}` | Primeiro nome |
|
||||||
|
| `{{lastName}}` | Sobrenome, quando existir |
|
||||||
|
| `{{produto}}` | Produto recomendado/interesse |
|
||||||
|
| `{{protocol}}` | Assunto/protocolo; fallback para produto |
|
||||||
|
| `{{cidade}}` | Cidade |
|
||||||
|
| `{{uf}}` | UF |
|
||||||
|
| `{{segmento}}` | Nicho/segmento |
|
||||||
|
| `{{cnpj}}` | CNPJ |
|
||||||
|
| `{{email}}` | E-mail |
|
||||||
|
| `{{phoneNumber}}` | WhatsApp/telefone |
|
||||||
|
| `{{whatsapp}}` | WhatsApp/telefone |
|
||||||
|
| `{{kanban}}` | Produto/interesse |
|
||||||
|
| `{{user}}` | Remetente |
|
||||||
|
| `{{userEmail}}` | E-mail do remetente |
|
||||||
|
| `{{greeting}}` | Saudacao |
|
||||||
|
|
||||||
Leads exportados ficam marcados — o filtro "ainda não exportados" evita reenvio.
|
Tambem existem placeholders legados: `{empresa}`, `{cidade}`, `{produto}` e `{segmento}`.
|
||||||
Os IDs padrão do Z-PRO (pipeline/etapa/responsável) ficam no ⚙️ Configurações.
|
|
||||||
|
|
||||||
> O `.xls` gerado é uma tabela HTML (o Excel avisa sobre o formato ao abrir — é normal,
|
## Exportacoes
|
||||||
> basta confirmar). Use o `.csv` se preferir.
|
|
||||||
|
|
||||||
## Qualidade dos leads (score)
|
| Tipo | Saida | Para que serve |
|
||||||
|
|---|---|---|
|
||||||
|
| Planilha | CSV + XLS | Analise comercial e tratamento externo |
|
||||||
|
| Z-PRO Oportunidades | JSONL | Payloads para criacao de oportunidades |
|
||||||
|
| Z-PRO Disparo em massa | CSV | `dataInput` para disparo em massa |
|
||||||
|
|
||||||
Score: +35 telefone válido, +25 CNPJ válido, +25 empresa válida, +5 cidade,
|
Leads exportados ficam marcados. Use o filtro de nao exportados para evitar retrabalho.
|
||||||
+5 nicho, +5 CNAE. **Bom ≥ 85**, médio 60–84, ruim < 60. Empresa vazia, com lixo
|
|
||||||
ou começando com número é sempre **ruim** (regra crítica). Duplicidade: CNPJ →
|
|
||||||
WhatsApp → empresa+cidade.
|
|
||||||
|
|
||||||
## Fontes de captura
|
## Score e Priorizacao
|
||||||
|
|
||||||
- **Base CNPJ (Receita Federal)** — principal: todas as empresas ativas da UF, ~97% com telefone.
|
O app calcula scores para ajudar o time comercial a decidir quem abordar primeiro.
|
||||||
- **OpenStreetMap** (Overpass e Nominatim) — grátis, complementar.
|
|
||||||
- **Wikidata** — grátis, volume baixo.
|
|
||||||
- **BrasilAPI** — enriquecimento opcional da base CNPJ.
|
|
||||||
- **Google Places** — paga; preencha `GOOGLE_MAPS_API_KEY` no `.env`.
|
|
||||||
|
|
||||||
## Novo estado (ex.: expandir para Sergipe)
|
Regras principais:
|
||||||
|
|
||||||
1. Na aba Captura, escolha **SE — Sergipe**.
|
- WhatsApp/telefone valido aumenta a prioridade.
|
||||||
2. Clique em **Extrair base agora** e aguarde (usa os zips já baixados em
|
- CNPJ valido aumenta a confiabilidade.
|
||||||
`prospeccao/cnpj/rfb-raw/`).
|
- Empresa valida, cidade, nicho, CNAE, website e e-mail melhoram o score.
|
||||||
3. Pronto: capture qualquer cidade de SE normalmente. Nada muda na interface.
|
- Nichos com maior aderencia comercial recebem mais peso.
|
||||||
|
- Leads sem WhatsApp podem continuar cadastrados, mas aparecem com prioridade menor.
|
||||||
|
- Duplicidade segue a ordem CNPJ, telefone, empresa+cidade.
|
||||||
|
|
||||||
Os zips brutos da Receita (7 GB, Brasil inteiro) já estão no projeto. Para atualizá-los
|
## Fontes de Captura
|
||||||
no futuro (a Receita publica mensalmente): `bash scripts/baixar-base-rfb.sh`.
|
|
||||||
|
|
||||||
## Uso avançado (linha de comando)
|
- Base CNPJ da Receita Federal: fonte principal para empresas ativas por UF.
|
||||||
|
- OpenStreetMap/Overpass: fonte aberta complementar.
|
||||||
|
- Nominatim: geocodificacao e apoio geografico.
|
||||||
|
- Wikidata: fonte aberta de baixo volume.
|
||||||
|
- BrasilAPI: enriquecimento de dados cadastrais.
|
||||||
|
- Google Places: fonte opcional paga, exige `GOOGLE_MAPS_API_KEY` no `.env`.
|
||||||
|
|
||||||
|
## Comandos
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm start # sobe o servidor
|
npm start
|
||||||
npm test # roda os testes
|
npm test
|
||||||
|
npm run capture
|
||||||
|
npm run extract
|
||||||
|
npm run recalc-scores
|
||||||
|
npm run outreach
|
||||||
|
npm run build:launcher
|
||||||
|
```
|
||||||
|
|
||||||
|
Exemplos:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node scripts/servidor.mjs
|
||||||
node scripts/capturar-leads.mjs --sources=cnpj-base --uf=BA --cities="Ilheus"
|
node scripts/capturar-leads.mjs --sources=cnpj-base --uf=BA --cities="Ilheus"
|
||||||
node scripts/extrair-base-cnpj.mjs --uf=SP # extrai base de outra UF
|
node scripts/extrair-base-cnpj.mjs --uf=SP
|
||||||
|
node scripts/enviar-outreach.mjs
|
||||||
```
|
```
|
||||||
|
|
||||||
## Estrutura do projeto
|
## Estrutura
|
||||||
|
|
||||||
```
|
```text
|
||||||
GTI-Comercial.exe inicia tudo (servidor + navegador)
|
GTI-Comercial.exe Launcher local do app
|
||||||
scripts/ entradas de linha de comando
|
INICIAR-GTI.bat Inicializacao alternativa no Windows
|
||||||
src/ código do servidor, fontes de captura, exportações
|
scripts/ Entradas de linha de comando
|
||||||
public/ interface (HTML/CSS/JS)
|
src/ Codigo do servidor e regras de negocio
|
||||||
data/gti.db banco local (SQLite) com todos os leads
|
src/server/ HTTP, rotas, sessoes e autenticacao
|
||||||
data/exports/ arquivos de exportação gerados
|
src/capture/ Pipeline de captura
|
||||||
prospeccao/cnpj/ base CNPJ extraída por UF + zips brutos da Receita
|
src/sources/ Fontes de dados
|
||||||
docs/ playbook comercial, LGPD e referência da API Z-PRO
|
src/treatment/ Consultas e dashboard de tratamento
|
||||||
|
src/export/ Exportacoes Excel/CSV/Z-PRO
|
||||||
|
src/outreach/ Z-PRO, templates WABA e automacao WhatsApp
|
||||||
|
public/ Interface HTML/CSS/JS
|
||||||
|
tests/ Testes automatizados
|
||||||
|
data/gti.db Banco SQLite local, nao versionado
|
||||||
|
data/exports/ Arquivos exportados, nao versionado
|
||||||
|
prospeccao/cnpj/ Base CNPJ e dados brutos da Receita
|
||||||
|
docs/ Documentacao complementar
|
||||||
|
.env Segredos locais, nao versionado
|
||||||
```
|
```
|
||||||
|
|
||||||
## Requisitos
|
## Requisitos
|
||||||
|
|
||||||
- Windows com **Node.js 24+** (https://nodejs.org)
|
- Windows.
|
||||||
- Para extrair novas UFs: `unzip` (vem com o Git para Windows) ou o `tar` nativo do Windows
|
- Node.js 24 ou superior.
|
||||||
|
- Para extrair novas UFs, `unzip`, Git Bash ou `tar` nativo do Windows.
|
||||||
|
|
||||||
## Log e problemas
|
## Seguranca e Dados
|
||||||
|
|
||||||
- Log do servidor: `data/server.log`
|
- O banco principal fica em `data/gti.db`.
|
||||||
- Se a tela não abrir: rode `node scripts/servidor.mjs` num terminal e veja a mensagem.
|
- Segredos locais devem ficar no `.env` ou nas configuracoes locais do app.
|
||||||
|
- Tokens Z-PRO/GChat nao devem ser commitados.
|
||||||
|
- A zona de risco em Configuracoes apaga leads, capturas e exportacoes; a acao e irreversivel.
|
||||||
|
- Nao ha backup automatico do banco local.
|
||||||
|
|
||||||
|
## Problemas Comuns
|
||||||
|
|
||||||
|
- Se a tela nao abrir, reinicie por `GTI-Comercial.exe` ou `INICIAR-GTI.bat`.
|
||||||
|
- Se preferir depurar, rode `node scripts/servidor.mjs` no terminal.
|
||||||
|
- Log do servidor: `data/server.log`.
|
||||||
|
- Se a sincronizacao de templates GChat falhar com erro de token, gere/salve um token GChat valido novamente.
|
||||||
|
- Se um template WABA falhar no Z-PRO, teste outro template aprovado e confira rota, idioma e variaveis obrigatorias.
|
||||||
|
|||||||
+10
-3
@@ -24,9 +24,12 @@ GTI-Comercial.exe → servidor Node local (porta 3900) → navegador
|
|||||||
└── Tratamento: dashboard, filtros, relatórios e exportações Z-PRO
|
└── Tratamento: dashboard, filtros, relatórios e exportações Z-PRO
|
||||||
```
|
```
|
||||||
|
|
||||||
Sem n8n, sem Docker, sem serviços externos obrigatórios: tudo roda no computador
|
Sem n8n, sem serviços externos obrigatórios: tudo roda no computador da GTI hoje
|
||||||
da GTI. O envio das mensagens é feito por fora (Z-PRO), a partir dos arquivos
|
(e vai rodar num container Docker no Proxmox da empresa no futuro, sem mudança de
|
||||||
gerados pelo módulo de tratamento.
|
código). O primeiro contato via WhatsApp pode ser automático (ver
|
||||||
|
[08-automacao-envio.md](08-automacao-envio.md)); campanhas maiores e o
|
||||||
|
acompanhamento seguem por fora, no Z-PRO, a partir dos arquivos gerados pelo
|
||||||
|
módulo de tratamento.
|
||||||
|
|
||||||
## Premissas
|
## Premissas
|
||||||
|
|
||||||
@@ -53,3 +56,7 @@ gerados pelo módulo de tratamento.
|
|||||||
- Acesso protegido por login (usuário/senha): o primeiro acesso vem com
|
- Acesso protegido por login (usuário/senha): o primeiro acesso vem com
|
||||||
`admin`/`admin`, que pode cadastrar novos usuários (comercial ou admin)
|
`admin`/`admin`, que pode cadastrar novos usuários (comercial ou admin)
|
||||||
pela tela de Usuários.
|
pela tela de Usuários.
|
||||||
|
- Automação de primeiro contato via WhatsApp (opcional, desligada por padrão):
|
||||||
|
manda uma mensagem com o template do produto recomendado pra cada lead ainda
|
||||||
|
não exportado, registra o que foi mandado e aplica tags no contato do Z-PRO —
|
||||||
|
ver [08-automacao-envio.md](08-automacao-envio.md).
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Automação de envio WhatsApp (Z-PRO)
|
||||||
|
|
||||||
|
Manda automaticamente a primeira mensagem de WhatsApp pro produto/serviço
|
||||||
|
recomendado de cada lead, usando um template por produto, e registra tudo
|
||||||
|
(quem recebeu, qual produto, quando) pra nunca mandar a mesma coisa duas
|
||||||
|
vezes pro mesmo lead.
|
||||||
|
|
||||||
|
## Como funciona
|
||||||
|
|
||||||
|
- Roda **sozinha, dentro do próprio servidor**, a cada 20 minutos, enquanto
|
||||||
|
o app estiver ligado — não depende de Agendador de Tarefas do Windows nem
|
||||||
|
de cron. Isso é de propósito: o projeto hoje roda local, mas vai ser
|
||||||
|
migrado pra um container Docker no Proxmox da empresa, e um agendador do
|
||||||
|
sistema operacional teria que ser reconfigurado nesse dia. O timer interno
|
||||||
|
funciona idêntico nos dois ambientes.
|
||||||
|
- Só considera leads **ainda não exportados** (`exported_at` vazio). Assim
|
||||||
|
que um lead vira oportunidade manual no Z-PRO (exportação normal da tela
|
||||||
|
de Tratamento), a automação para de mandar mensagem pra ele — quem assumiu
|
||||||
|
o lead foi um vendedor, não o robô.
|
||||||
|
- Cada lead tem uma lista de produtos recomendados por nicho (ex.: ERP 5⭐,
|
||||||
|
G-Delivery 3⭐). Hoje a automação só tenta o **produto principal** (o de
|
||||||
|
maior estrela), uma única vez por lead. Existe uma segunda etapa pronta
|
||||||
|
(mas desligada) pra tentar o próximo produto da lista se não houver
|
||||||
|
resposta depois de alguns dias — ver `outreach.tentarProximoProduto`
|
||||||
|
abaixo.
|
||||||
|
- Manda uma mensagem por número, com controle nosso de quem já recebeu o
|
||||||
|
quê — não pelo `bulkSendMessageWithVariable` usado na exportação manual
|
||||||
|
em massa, que depende de um CSV com substituição posicional de variável.
|
||||||
|
Cada produto tem um **canal** próprio (ver seção abaixo).
|
||||||
|
- Depois de mandar, aplica duas tags no contato do Z-PRO:
|
||||||
|
`GTI P1`/`GTI P2`/`GTI P3`/`GTI P4` (prioridade do lead) e
|
||||||
|
`GTI Oferta: <produto>` (o que foi ofertado) — pra quem for atender depois
|
||||||
|
já ver esse contexto direto na conversa.
|
||||||
|
|
||||||
|
## Canal oficial x não-oficial
|
||||||
|
|
||||||
|
Cada produto/template tem um seletor de canal em Configurações:
|
||||||
|
|
||||||
|
- **Não-oficial (texto livre)** — usa `bulkIndividual`, funciona numa
|
||||||
|
conexão QR Code/Baileys do Z-PRO. Manda o texto do template com
|
||||||
|
`{empresa}`/`{cidade}`/`{segmento}` substituídos. É o padrão, e o risco
|
||||||
|
aqui é o de sempre com WhatsApp não-oficial: possibilidade de bloqueio do
|
||||||
|
número por comportamento automatizado (por isso o limite diário e o
|
||||||
|
intervalo aleatório entre envios).
|
||||||
|
- **Oficial (Meta, template aprovado)** — usa a API oficial do WhatsApp
|
||||||
|
(Cloud API/WABA) via Z-PRO. Aqui **não dá pra mandar texto livre**: o
|
||||||
|
WhatsApp só permite iniciar uma conversa com um **template pré-aprovado**
|
||||||
|
pelo Meta Business Manager (fora da janela de 24h de uma conversa já
|
||||||
|
iniciada pelo cliente). Por isso o campo vira "Nome do template aprovado"
|
||||||
|
(tem que ser **exatamente** o nome cadastrado no Meta) + "Idioma" (ex.:
|
||||||
|
`pt_BR`).
|
||||||
|
|
||||||
|
**A aprovação do template em si é feita fora deste app** — no Meta
|
||||||
|
Business Manager (ou no painel do Z-PRO, se ele tiver essa tela) — o
|
||||||
|
Z-PRO só expõe o *envio* usando um template que já existe, não a criação.
|
||||||
|
Cadastre e espere aprovar lá antes de configurar o nome aqui.
|
||||||
|
|
||||||
|
Limitação atual: o envio oficial aqui é só nome+idioma, sem variáveis
|
||||||
|
dentro do corpo do template aprovado (a API do Z-PRO tem endpoints
|
||||||
|
`templateBody`/`templateMarketingBody` que parecem aceitar variáveis, mas
|
||||||
|
o formato exato não está documentado na collection — se for necessário,
|
||||||
|
precisa testar contra a instância real antes de automatizar).
|
||||||
|
|
||||||
|
## Configurar pela primeira vez
|
||||||
|
|
||||||
|
1. **Credenciais do Z-PRO**: no painel do Z-PRO, vá em Admin > API e gere um
|
||||||
|
token (Base URL, API ID, Token e WhatsApp ID). Na tela, abra
|
||||||
|
**⚙️ Configurações > Credenciais Z-PRO (WhatsApp)**, preencha os 4 campos
|
||||||
|
e clique em **Testar conexão** (salva e faz uma chamada real e barata pra
|
||||||
|
confirmar que as credenciais estão certas, sem mandar nenhuma mensagem).
|
||||||
|
Sem essas 4 credenciais a automação não manda nada, mesmo ligada.
|
||||||
|
|
||||||
|
Alternativa pra quem prefere não guardar o token no banco local (ex.: em
|
||||||
|
produção no Docker/Proxmox, gerenciando segredo por variável de
|
||||||
|
ambiente): deixe os 4 campos da tela em branco e defina
|
||||||
|
`ZPRO_BASE_URL`/`ZPRO_API_ID`/`ZPRO_BEARER_TOKEN`/`ZPRO_WHATSAPP_ID` no
|
||||||
|
`.env` — a tela vazia cai automaticamente pro `.env`. Se a tela tiver
|
||||||
|
algum valor preenchido, ele tem prioridade sobre o `.env`.
|
||||||
|
2. Na mesma tela, em **Automação de envio (WhatsApp)**: revise o texto de
|
||||||
|
cada template (um por produto — `{empresa}`, `{cidade}` e `{segmento}`
|
||||||
|
são substituídos automaticamente), ajuste o **limite por dia** se
|
||||||
|
quiser, e marque **Ativada**. Salve.
|
||||||
|
|
||||||
|
Antes de ativar, vale mandar um teste manual (próxima seção) pro seu
|
||||||
|
próprio WhatsApp.
|
||||||
|
|
||||||
|
## Configurações (`settings`, chave → o que faz)
|
||||||
|
|
||||||
|
| Chave | Padrão | O que faz |
|
||||||
|
|---|---|---|
|
||||||
|
| `outreach.ativo` | `false` | Interruptor geral. Começa desligado de propósito. |
|
||||||
|
| `outreach.mensagensPorDia` | `10` | Máximo de envios automáticos por dia (soma de todos os produtos). |
|
||||||
|
| `outreach.diasEntreProdutos` | `5` | Dias de espera antes de tentar o próximo produto (só usado se a cascata estiver ligada). |
|
||||||
|
| `outreach.tentarProximoProduto` | `false` | Liga a cascata: quando `false`, só tenta o produto principal uma vez. |
|
||||||
|
| `outreach.horaInicio` / `outreach.horaFim` | `08:00` / `18:00` | Só manda mensagem dentro desse horário. |
|
||||||
|
|
||||||
|
Tudo isso é editável pela tela de Configurações (os dois primeiros) ou
|
||||||
|
diretamente via `PUT /api/settings` (todos).
|
||||||
|
|
||||||
|
## Disparo manual (fora do ciclo automático)
|
||||||
|
|
||||||
|
Pra testar ou forçar um lote sem esperar o próximo ciclo de 20 min:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run outreach
|
||||||
|
```
|
||||||
|
|
||||||
|
Respeita as mesmas regras do ciclo automático (`outreach.ativo`, horário
|
||||||
|
comercial, limite diário) — não manda nada que a tela não mostraria.
|
||||||
|
|
||||||
|
## Enviar pra um número específico
|
||||||
|
|
||||||
|
Em **Configurações > Enviar mensagem manual**: digite o número (com DDI+DDD,
|
||||||
|
ex.: `5511999999999`), escolha o canal (texto livre ou template oficial já
|
||||||
|
aprovado) e clique em Enviar. Não depende de lead cadastrado nem de produto.
|
||||||
|
|
||||||
|
No canal **Não-oficial (texto livre)**, o app usa `createTicket` para criar uma
|
||||||
|
conversa visível no painel do Z-PRO. O ticket usa o canal informado em
|
||||||
|
`WhatsApp ID` e o usuário de `Responsável` nas configurações.
|
||||||
|
|
||||||
|
No canal **Oficial**, o app usa o endpoint de template aprovado (`template`) e
|
||||||
|
também espera um `ticketId` na resposta.
|
||||||
|
|
||||||
|
Toda tentativa fica registrada no mesmo histórico dos envios automáticos
|
||||||
|
(marcado como origem "manual") e **conta pro limite diário**, já que o risco de
|
||||||
|
bloqueio é do número de WhatsApp usado, não de quem disparou a mensagem.
|
||||||
|
|
||||||
|
## Onde fica o histórico
|
||||||
|
|
||||||
|
Toda tentativa de envio (sucesso ou erro) vira uma linha na tabela
|
||||||
|
`outreach_sends` (lead, produto, mensagem exata mandada, status, quando).
|
||||||
|
Um resumo do dia (enviados hoje, por produto, últimos 20 envios) fica
|
||||||
|
disponível em `GET /api/outreach/status`.
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Generated
+15
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "gti-maquina-comercial",
|
||||||
|
"version": "2.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "gti-maquina-comercial",
|
||||||
|
"version": "2.0.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
"capture": "node scripts/capturar-leads.mjs",
|
"capture": "node scripts/capturar-leads.mjs",
|
||||||
"extract": "node scripts/extrair-base-cnpj.mjs",
|
"extract": "node scripts/extrair-base-cnpj.mjs",
|
||||||
"recalc-scores": "node scripts/recalcular-scores.mjs",
|
"recalc-scores": "node scripts/recalcular-scores.mjs",
|
||||||
|
"outreach": "node scripts/enviar-outreach.mjs",
|
||||||
"build:launcher": "powershell -File scripts/build-launcher.ps1"
|
"build:launcher": "powershell -File scripts/build-launcher.ps1"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
|
|||||||
@@ -11,16 +11,23 @@ O captador aceita CSV com cabecalho e tenta reconhecer colunas comuns como:
|
|||||||
- `cnae`, `cnae_fiscal` ou `cnae principal`
|
- `cnae`, `cnae_fiscal` ou `cnae principal`
|
||||||
- `logradouro`, `numero`, `bairro`
|
- `logradouro`, `numero`, `bairro`
|
||||||
|
|
||||||
Comando para usar a base local:
|
Comando para extrair a base de uma UF a partir dos zips brutos da Receita
|
||||||
|
(gera o CSV `estabelecimentos-<UF>.csv` usado pela captura):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run prospect -- --source=cnpj-base --send
|
npm run extract -- --uf=BA
|
||||||
```
|
```
|
||||||
|
|
||||||
Com enriquecimento pela BrasilAPI, use:
|
Comando para capturar leads usando a base já extraída:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run prospect -- --source=brasilapi --send
|
npm run capture -- --sources=cnpj-base --uf=BA --cities="Ilheus"
|
||||||
|
```
|
||||||
|
|
||||||
|
Com enriquecimento pela BrasilAPI, inclua a fonte `brasilapi`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run capture -- --sources=cnpj-base,brasilapi --uf=BA --cities="Ilheus"
|
||||||
```
|
```
|
||||||
|
|
||||||
O modo `brasilapi` usa os CNPJs encontrados nos CSVs locais para consultar dados atualizados por CNPJ.
|
O modo `brasilapi` usa os CNPJs encontrados nos CSVs locais para consultar dados atualizados por CNPJ.
|
||||||
|
|||||||
+618
-245
@@ -1,323 +1,696 @@
|
|||||||
/* GTI Máquina Comercial — tokens de design (paleta validada, light/dark) */
|
/* GTI Maquina Comercial - interface principal */
|
||||||
:root {
|
:root {
|
||||||
--page: #f9f9f7;
|
--page: #f5f7fb;
|
||||||
--surface: #fcfcfb;
|
--page-2: #eef2f7;
|
||||||
--ink: #0b0b0b;
|
--surface: #ffffff;
|
||||||
--ink-2: #52514e;
|
--surface-2: #f9fafc;
|
||||||
--muted: #898781;
|
--ink: #162033;
|
||||||
--grid: #e1e0d9;
|
--ink-2: #4c5870;
|
||||||
--border: rgba(11, 11, 11, 0.10);
|
--muted: #7b8495;
|
||||||
--accent: #2a78d6; /* series-1 azul */
|
--grid: #dce2ec;
|
||||||
|
--border: rgba(22, 32, 51, 0.11);
|
||||||
|
--accent: #f06a25;
|
||||||
|
--accent-2: #1f6feb;
|
||||||
--accent-ink: #ffffff;
|
--accent-ink: #ffffff;
|
||||||
--bar: #5598e7; /* sequential 350 — barras de ranking */
|
--bar: #f06a25;
|
||||||
--good: #0ca30c;
|
--good: #10a66a;
|
||||||
--good-text: #006300;
|
--good-text: #057046;
|
||||||
--warning: #fab219;
|
--warning: #d99a1f;
|
||||||
--critical: #d03b3b;
|
--critical: #d63d4a;
|
||||||
--shadow: 0 1px 3px rgba(11, 11, 11, 0.08);
|
--critical-bg: #fff1f2;
|
||||||
|
--radius-sm: 10px;
|
||||||
|
--radius: 16px;
|
||||||
|
--radius-lg: 24px;
|
||||||
|
--shadow: 0 14px 40px rgba(22, 32, 51, 0.08);
|
||||||
|
--shadow-soft: 0 8px 24px rgba(22, 32, 51, 0.06);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
:root {
|
:root {
|
||||||
--page: #0d0d0d;
|
--page: #0d1118;
|
||||||
--surface: #1a1a19;
|
--page-2: #111827;
|
||||||
--ink: #ffffff;
|
--surface: #171c27;
|
||||||
--ink-2: #c3c2b7;
|
--surface-2: #1d2430;
|
||||||
--muted: #898781;
|
--ink: #f5f7fb;
|
||||||
--grid: #2c2c2a;
|
--ink-2: #c8d0dd;
|
||||||
--border: rgba(255, 255, 255, 0.10);
|
--muted: #8e98aa;
|
||||||
--accent: #3987e5;
|
--grid: #2c3443;
|
||||||
--bar: #3987e5;
|
--border: rgba(255, 255, 255, 0.11);
|
||||||
--good-text: #0ca30c;
|
--accent: #ff7a33;
|
||||||
--shadow: none;
|
--accent-2: #60a5fa;
|
||||||
|
--bar: #ff7a33;
|
||||||
|
--good-text: #55d99c;
|
||||||
|
--critical-bg: rgba(214, 61, 74, 0.12);
|
||||||
|
--shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
|
||||||
|
--shadow-soft: 0 10px 28px rgba(0, 0, 0, 0.22);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
html, body { margin: 0; padding: 0; }
|
html, body { margin: 0; padding: 0; min-height: 100%; }
|
||||||
body {
|
body {
|
||||||
background: var(--page);
|
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
|
font: 14px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at 12% -10%, color-mix(in srgb, var(--accent) 16%, transparent), transparent 34rem),
|
||||||
|
radial-gradient(circle at 86% -6%, color-mix(in srgb, var(--accent-2) 12%, transparent), transparent 30rem),
|
||||||
|
linear-gradient(180deg, var(--page), var(--page-2));
|
||||||
}
|
}
|
||||||
|
button, input, select, textarea { font: inherit; }
|
||||||
|
button { color: inherit; }
|
||||||
|
|
||||||
/* ---------- topo ---------- */
|
/* topo */
|
||||||
.topbar {
|
.topbar {
|
||||||
display: flex; align-items: center; gap: 20px;
|
position: sticky;
|
||||||
padding: 10px 20px;
|
top: 0;
|
||||||
background: var(--surface);
|
z-index: 20;
|
||||||
border-bottom: 1px solid var(--grid);
|
display: grid;
|
||||||
position: sticky; top: 0; z-index: 20;
|
grid-template-columns: auto minmax(220px, 1fr) auto auto auto auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 22px;
|
||||||
|
background: color-mix(in srgb, var(--surface) 88%, transparent);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
box-shadow: 0 8px 30px rgba(22, 32, 51, 0.04);
|
||||||
|
backdrop-filter: blur(14px);
|
||||||
}
|
}
|
||||||
.brand { display: flex; align-items: baseline; gap: 8px; }
|
.brand { display: flex; align-items: center; gap: 10px; min-width: max-content; }
|
||||||
.brand-mark {
|
.brand-mark { height: 32px; width: auto; display: block; border-radius: 8px; }
|
||||||
background: var(--accent); color: var(--accent-ink);
|
.brand-mark-lg { height: 62px; }
|
||||||
font-weight: 800; padding: 3px 9px; border-radius: 6px; letter-spacing: 0.5px;
|
.brand-name { font-weight: 800; letter-spacing: -0.02em; color: var(--ink); }
|
||||||
|
.tabs {
|
||||||
|
display: inline-flex;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 4px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
width: fit-content;
|
||||||
}
|
}
|
||||||
.brand-name { font-weight: 600; color: var(--ink-2); }
|
|
||||||
.tabs { display: flex; gap: 4px; flex: 1; }
|
|
||||||
.tab {
|
.tab {
|
||||||
border: none; background: none; color: var(--ink-2);
|
border: 0;
|
||||||
font: inherit; font-weight: 600; padding: 8px 16px;
|
border-radius: 999px;
|
||||||
border-radius: 8px; cursor: pointer;
|
background: transparent;
|
||||||
|
color: var(--ink-2);
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 750;
|
||||||
|
padding: 8px 14px;
|
||||||
|
transition: 0.18s ease;
|
||||||
}
|
}
|
||||||
.tab:hover { background: var(--grid); }
|
.tab:hover { color: var(--ink); background: color-mix(in srgb, var(--accent) 9%, transparent); }
|
||||||
.tab.active { background: var(--accent); color: var(--accent-ink); }
|
.tab.active { background: var(--ink); color: var(--page); box-shadow: var(--shadow-soft); }
|
||||||
|
|
||||||
main { max-width: 1280px; margin: 0 auto; padding: 16px 20px 60px; }
|
main { max-width: 1320px; margin: 0 auto; padding: 24px 22px 70px; }
|
||||||
.tab-panel { display: none; }
|
.tab-panel { display: none; }
|
||||||
.tab-panel.active { display: block; }
|
.tab-panel.active { display: block; }
|
||||||
|
|
||||||
/* ---------- cartões e grades ---------- */
|
/* layout */
|
||||||
|
.captura-wrap { max-width: 820px; margin: 0 auto; }
|
||||||
.card {
|
.card {
|
||||||
background: var(--surface);
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
background: color-mix(in srgb, var(--surface) 96%, transparent);
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
border-radius: 12px;
|
border-radius: var(--radius-lg);
|
||||||
padding: 16px 18px;
|
box-shadow: var(--shadow-soft);
|
||||||
box-shadow: var(--shadow);
|
padding: 20px;
|
||||||
margin-bottom: 16px;
|
margin-bottom: 18px;
|
||||||
}
|
|
||||||
.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; }
|
|
||||||
}
|
}
|
||||||
|
.card h2 { margin: 0 0 14px; font-size: 18px; letter-spacing: -0.02em; }
|
||||||
|
.grid-3 { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
|
||||||
|
|
||||||
/* ---------- formulários ---------- */
|
/* formularios */
|
||||||
.field { margin-bottom: 18px; }
|
.field { margin-bottom: 18px; }
|
||||||
.field > label:first-child, .field > summary { font-weight: 600; display: block; margin-bottom: 6px; }
|
.field > label:first-child,
|
||||||
.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
|
.field > summary,
|
||||||
|
label.settings-title {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 7px;
|
||||||
|
color: var(--ink);
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||||
.row.space-between { justify-content: space-between; }
|
.row.space-between { justify-content: space-between; }
|
||||||
.row.wrap { flex-wrap: wrap; }
|
.row.wrap { flex-wrap: wrap; }
|
||||||
.radio { display: flex; align-items: center; gap: 6px; font-weight: 400; cursor: pointer; margin: 4px 0; }
|
label { color: var(--ink-2); }
|
||||||
select, input, textarea {
|
label > input,
|
||||||
font: inherit; color: var(--ink);
|
label > select,
|
||||||
background: var(--page);
|
label > textarea { display: block; margin-top: 5px; }
|
||||||
border: 1px solid var(--grid);
|
.radio {
|
||||||
border-radius: 8px; padding: 7px 10px;
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin: 4px 0;
|
||||||
|
color: var(--ink-2);
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
}
|
}
|
||||||
select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); outline-offset: 1px; }
|
input[type="radio"], input[type="checkbox"] { accent-color: var(--accent); }
|
||||||
input[type="number"] { width: 90px; }
|
select, input, textarea {
|
||||||
label > input[type="number"] { display: block; margin-top: 4px; }
|
width: auto;
|
||||||
|
color: var(--ink);
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--grid);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.35);
|
||||||
|
transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease;
|
||||||
|
}
|
||||||
|
textarea { width: 100%; resize: vertical; min-height: 84px; }
|
||||||
|
select:hover, input:hover, textarea:hover { border-color: color-mix(in srgb, var(--accent) 38%, var(--grid)); }
|
||||||
|
select:focus, input:focus, textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent);
|
||||||
|
box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 15%, transparent);
|
||||||
|
}
|
||||||
|
input[type="number"] { width: 96px; }
|
||||||
details summary { cursor: pointer; }
|
details summary { cursor: pointer; }
|
||||||
|
|
||||||
|
/* botoes */
|
||||||
.btn, .btn-ghost, .btn-danger {
|
.btn, .btn-ghost, .btn-danger {
|
||||||
font: inherit; font-weight: 600; cursor: pointer;
|
display: inline-flex;
|
||||||
border-radius: 8px; padding: 8px 14px;
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-height: 40px;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 9px 15px;
|
||||||
border: 1px solid var(--grid);
|
border: 1px solid var(--grid);
|
||||||
background: var(--surface); color: var(--ink);
|
background: var(--surface);
|
||||||
|
color: var(--ink);
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 800;
|
||||||
|
text-decoration: none;
|
||||||
|
transition: 0.18s ease;
|
||||||
}
|
}
|
||||||
.btn:hover, .btn-ghost:hover { border-color: var(--accent); }
|
.btn:hover, .btn-ghost:hover { transform: translateY(-1px); border-color: var(--accent); box-shadow: var(--shadow-soft); }
|
||||||
.btn-primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
|
.btn-primary { background: linear-gradient(135deg, var(--accent), #ff8b47); border-color: transparent; color: var(--accent-ink); }
|
||||||
.btn-primary:hover { filter: brightness(1.1); }
|
.btn-primary:hover { filter: saturate(1.08); }
|
||||||
.btn-lg { width: 100%; padding: 12px; font-size: 15px; }
|
.btn-lg { width: 100%; min-height: 48px; font-size: 15px; }
|
||||||
.btn-ghost { border-color: transparent; color: var(--ink-2); }
|
.btn-sm { min-height: 32px; padding: 6px 10px; font-size: 12.5px; }
|
||||||
.btn-danger { color: var(--critical); border-color: var(--critical); background: none; }
|
.btn-ghost { border-color: transparent; background: transparent; color: var(--ink-2); }
|
||||||
.btn-danger:hover { background: var(--critical); color: #fff; }
|
.btn-danger { color: var(--critical); border-color: color-mix(in srgb, var(--critical) 45%, var(--grid)); background: color-mix(in srgb, var(--critical) 6%, transparent); }
|
||||||
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
.btn-danger:hover { background: var(--critical); color: #fff; border-color: var(--critical); }
|
||||||
|
button:disabled { opacity: 0.55; cursor: not-allowed; transform: none !important; box-shadow: none !important; }
|
||||||
|
|
||||||
.zona-risco { border: 1px solid var(--critical); border-radius: 10px; padding: 10px 12px; margin-top: 14px; }
|
/* configuracoes */
|
||||||
.zona-risco label { color: var(--critical); font-weight: 700; }
|
#modal-settings { max-width: 900px; }
|
||||||
|
#modal-settings .modal-body { max-height: min(86vh, 900px); overflow-y: auto; }
|
||||||
|
.settings-header {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
gap: 16px;
|
||||||
|
align-items: start;
|
||||||
|
padding-bottom: 14px;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.settings-header h2 { margin: 0 0 4px; font-size: 24px; letter-spacing: -0.03em; }
|
||||||
|
.settings-header p { margin: 0; }
|
||||||
|
#outreach-status { cursor: default; white-space: nowrap; }
|
||||||
|
.settings-card,
|
||||||
|
.settings-section {
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface-2);
|
||||||
|
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.34) inset;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.settings-card { padding: 16px; }
|
||||||
|
.settings-principal {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
gap: 18px;
|
||||||
|
align-items: center;
|
||||||
|
border-color: color-mix(in srgb, var(--accent) 38%, var(--border));
|
||||||
|
background: linear-gradient(135deg, color-mix(in srgb, var(--accent) 10%, var(--surface)), var(--surface-2));
|
||||||
|
}
|
||||||
|
.settings-controls { display: flex; gap: 12px; align-items: end; flex-wrap: wrap; justify-content: flex-end; }
|
||||||
|
.toggle {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-height: 42px;
|
||||||
|
border: 1px solid var(--grid);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 8px 13px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--ink);
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
.settings-section { padding: 0 16px 16px; }
|
||||||
|
.settings-section > summary {
|
||||||
|
position: relative;
|
||||||
|
list-style: none;
|
||||||
|
padding: 15px 30px 15px 0;
|
||||||
|
color: var(--ink);
|
||||||
|
font-weight: 850;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
.settings-section > summary::-webkit-details-marker { display: none; }
|
||||||
|
.settings-section > summary::after {
|
||||||
|
content: "+";
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
top: 13px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 50%;
|
||||||
|
color: var(--ink-2);
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--grid);
|
||||||
|
}
|
||||||
|
.settings-section[open] > summary::after { content: "-"; }
|
||||||
|
.settings-section > .muted { margin-top: -4px; }
|
||||||
|
.settings-section .lista { margin-top: 10px; }
|
||||||
|
.settings-section input[type="text"],
|
||||||
|
.settings-section input[type="password"],
|
||||||
|
.settings-section textarea,
|
||||||
|
.settings-section select { min-width: 220px; }
|
||||||
|
|
||||||
/* ---------- login ---------- */
|
.manual-send-card {
|
||||||
.login-body { display: flex; min-height: 100vh; }
|
display: grid;
|
||||||
.login-wrap { margin: auto; width: 100%; max-width: 360px; padding: 20px; }
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
.login-card { display: flex; flex-direction: column; gap: 14px; }
|
gap: 14px;
|
||||||
.login-brand { justify-content: center; margin-bottom: 4px; }
|
padding: 14px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.manual-send-card .full { grid-column: 1 / -1; }
|
||||||
|
.manual-channel {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.manual-channel .radio {
|
||||||
|
border: 1px solid var(--grid);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
font-weight: 750;
|
||||||
|
}
|
||||||
|
#manual-oficial-campos {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
#manual-oficial-campos.hidden { display: none !important; }
|
||||||
|
#manual-template-nome { min-width: 0; width: 100%; }
|
||||||
|
.template-vars {
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px dashed var(--grid);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface-2);
|
||||||
|
}
|
||||||
|
.template-vars > label { color: var(--ink); font-weight: 800; }
|
||||||
|
.template-vars p { margin: 2px 0 10px; }
|
||||||
|
.variable-helper {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
.variable-helper select, .variable-picker { min-width: min(100%, 320px); }
|
||||||
|
.template-vars-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.template-vars-grid label:last-child { grid-column: 1 / -1; }
|
||||||
|
.template-preview {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--ink-2);
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
.manual-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding-top: 4px;
|
||||||
|
}
|
||||||
|
#manual-status:not(:empty) {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--surface-2);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
#manual-status:not(:empty)::first-letter { font-weight: 900; }
|
||||||
|
#manual-status:not(:empty) { color: var(--ink-2); }
|
||||||
|
#manual-status.status-ok { color: var(--good-text); background: color-mix(in srgb, var(--good) 10%, var(--surface)); border-color: color-mix(in srgb, var(--good) 28%, var(--border)); }
|
||||||
|
#manual-status.status-error { color: var(--critical); background: var(--critical-bg); border-color: color-mix(in srgb, var(--critical) 30%, var(--border)); }
|
||||||
|
#btn-toggle-outreach-log { justify-self: start; margin-top: 2px; }
|
||||||
|
|
||||||
|
.outreach-template { flex-direction: column; align-items: stretch; gap: 8px; }
|
||||||
|
.outreach-template .row.space-between { align-items: center; }
|
||||||
|
.outreach-template textarea { width: 100%; margin-top: 2px; }
|
||||||
|
.outreach-template-oficial { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.outreach-template-vars { margin-top: 2px; }
|
||||||
|
.outreach-template-vars .template-vars-grid { grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); }
|
||||||
|
.outreach-template-vars .template-vars-grid label:last-child { grid-column: auto; }
|
||||||
|
.outreach-template-link { color: var(--accent-2); font-size: 12.5px; font-weight: 750; text-decoration: none; }
|
||||||
|
.outreach-template-link:hover { text-decoration: underline; }
|
||||||
|
.outreach-template-aviso { color: var(--critical); font-size: 12.5px; margin: 0; }
|
||||||
|
#outreach-limite { width: 82px; }
|
||||||
|
|
||||||
|
.zona-risco { border-color: color-mix(in srgb, var(--critical) 45%, var(--border)); background: color-mix(in srgb, var(--critical) 5%, var(--surface)); }
|
||||||
|
.zona-risco summary { color: var(--critical); }
|
||||||
|
.template-sync-box {
|
||||||
|
margin-top: 14px;
|
||||||
|
padding-top: 14px;
|
||||||
|
border-top: 1px dashed var(--grid);
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(220px, 0.45fr);
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.template-sync-box .row { grid-column: 1 / -1; }
|
||||||
|
.template-sync-inline {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* login */
|
||||||
|
.login-body {
|
||||||
|
display: flex;
|
||||||
|
min-height: 100vh;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at 18% 12%, color-mix(in srgb, var(--accent) 22%, transparent), transparent 28rem),
|
||||||
|
radial-gradient(circle at 82% 4%, color-mix(in srgb, var(--accent-2) 18%, transparent), transparent 26rem),
|
||||||
|
linear-gradient(135deg, var(--page), var(--page-2));
|
||||||
|
}
|
||||||
|
.login-wrap { margin: auto; width: 100%; max-width: 410px; padding: 22px; }
|
||||||
|
.login-card { display: flex; flex-direction: column; gap: 14px; padding: 28px; }
|
||||||
|
.login-brand { justify-content: center; margin-bottom: 6px; }
|
||||||
.login-erro { color: var(--critical); min-height: 1em; margin: 0; }
|
.login-erro { color: var(--critical); min-height: 1em; margin: 0; }
|
||||||
|
.erro { color: var(--critical); margin: 4px 0 0; font-weight: 750; }
|
||||||
|
.login-card .field input { width: 100%; }
|
||||||
|
|
||||||
/* ---------- usuarios ---------- */
|
/* chips, avisos e listas */
|
||||||
#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 {
|
.chip {
|
||||||
font-size: 12px; font-weight: 600;
|
display: inline-flex;
|
||||||
padding: 3px 10px; border-radius: 999px;
|
align-items: center;
|
||||||
background: var(--grid); color: var(--ink-2);
|
gap: 6px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--ink-2);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 5px 11px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 800;
|
||||||
}
|
}
|
||||||
.chip.ok { background: color-mix(in srgb, var(--good) 15%, transparent); color: var(--good-text); }
|
.chip.ok { background: color-mix(in srgb, var(--good) 12%, var(--surface)); color: var(--good-text); border-color: color-mix(in srgb, var(--good) 26%, var(--border)); }
|
||||||
.chip.warn { background: color-mix(in srgb, var(--warning) 20%, transparent); color: var(--ink); }
|
.chip.warn { background: color-mix(in srgb, var(--warning) 14%, var(--surface)); color: var(--ink); border-color: color-mix(in srgb, var(--warning) 32%, var(--border)); }
|
||||||
|
|
||||||
.notice {
|
.notice {
|
||||||
margin-top: 10px; padding: 12px;
|
margin-top: 12px;
|
||||||
border: 1px solid var(--warning);
|
padding: 14px;
|
||||||
border-radius: 8px;
|
border: 1px solid color-mix(in srgb, var(--warning) 42%, var(--border));
|
||||||
background: color-mix(in srgb, var(--warning) 8%, transparent);
|
border-radius: var(--radius);
|
||||||
|
background: color-mix(in srgb, var(--warning) 10%, var(--surface));
|
||||||
}
|
}
|
||||||
.notice p { margin: 0 0 10px; }
|
.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 { display: flex; flex-direction: column; gap: 8px; }
|
||||||
.lista .item {
|
.lista .item {
|
||||||
display: flex; justify-content: space-between; align-items: center; gap: 10px;
|
display: flex;
|
||||||
border-bottom: 1px solid var(--grid); padding: 8px 2px; flex-wrap: wrap;
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 11px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--surface);
|
||||||
}
|
}
|
||||||
.lista .item:last-child { border-bottom: none; }
|
.lista .item .sub { color: var(--muted); font-size: 12px; }
|
||||||
.lista .item .sub { font-size: 12px; color: var(--muted); }
|
|
||||||
|
|
||||||
/* ---------- tratamento: tiles e rankings ---------- */
|
/* pickers */
|
||||||
.filtros-card { padding: 12px 16px; }
|
.picker { margin-top: 10px; }
|
||||||
.filtros { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
.picker input[type="search"], .cnae-avulso input[type="search"] { width: 100%; margin-bottom: 8px; }
|
||||||
.filtros select, .filtros input { min-width: 130px; }
|
.sugestoes { display: flex; flex-direction: column; gap: 4px; max-height: 200px; overflow-y: auto; }
|
||||||
#f-busca { flex: 1; min-width: 200px; }
|
.sugestoes button {
|
||||||
|
text-align: left;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink);
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 8px 10px;
|
||||||
|
}
|
||||||
|
.sugestoes button:hover { background: var(--surface-2); }
|
||||||
|
.chips { display: flex; flex-wrap: wrap; gap: 7px; margin: 8px 0 12px; }
|
||||||
|
.chips .chip { cursor: pointer; }
|
||||||
|
.chips .chip::after { content: " x"; color: var(--muted); }
|
||||||
|
.chips .chip:hover { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, var(--surface)); }
|
||||||
|
.nichos-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));
|
||||||
|
gap: 4px 12px;
|
||||||
|
max-height: 320px;
|
||||||
|
overflow-y: auto;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
.nichos-grid label { display: flex; gap: 7px; align-items: center; padding: 6px 7px; border-radius: 10px; cursor: pointer; }
|
||||||
|
.nichos-grid label:hover { background: var(--surface-2); }
|
||||||
|
.cnae-avulso { margin-top: 14px; border-top: 1px dashed var(--grid); padding-top: 12px; }
|
||||||
|
.cnae-avulso summary { color: var(--ink-2); font-size: 13px; font-weight: 800; }
|
||||||
|
.cnae-avulso-hint { margin: 7px 0 9px; font-size: 12.5px; }
|
||||||
|
.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: 8px; }
|
||||||
|
.fonte {
|
||||||
|
display: flex;
|
||||||
|
gap: 11px;
|
||||||
|
align-items: flex-start;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 11px 12px;
|
||||||
|
background: var(--surface);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.fonte:hover { border-color: var(--accent); box-shadow: var(--shadow-soft); }
|
||||||
|
.fonte input { margin-top: 3px; }
|
||||||
|
.fonte .desc { color: var(--ink-2); font-size: 12.5px; }
|
||||||
|
.fonte.indisponivel { opacity: 0.58; }
|
||||||
|
|
||||||
.stat-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin-bottom: 16px; }
|
/* progresso */
|
||||||
|
.progress-bar { height: 10px; border-radius: 999px; background: var(--grid); overflow: hidden; margin: 12px 0 9px; }
|
||||||
|
.progress-fill { height: 100%; width: 3%; background: linear-gradient(90deg, var(--accent), #ffb36d); border-radius: 999px; transition: width 0.4s; }
|
||||||
|
.progress-msg { color: var(--ink-2); margin: 4px 0 11px; min-height: 1.4em; }
|
||||||
|
.stat-row { display: flex; gap: 18px; margin-bottom: 12px; flex-wrap: wrap; }
|
||||||
|
.stat-row .mini { display: flex; flex-direction: column; min-width: 96px; }
|
||||||
|
.stat-row .mini b { font-size: 23px; letter-spacing: -0.03em; }
|
||||||
|
.stat-row .mini span { color: var(--muted); font-size: 12px; }
|
||||||
|
.log {
|
||||||
|
max-height: 170px;
|
||||||
|
overflow-y: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
background: #0f172a;
|
||||||
|
color: #dbeafe;
|
||||||
|
font: 12px/1.55 ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tratamento */
|
||||||
|
.filtros-card { padding: 14px; }
|
||||||
|
.filtros { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 9px; align-items: center; }
|
||||||
|
.filtros select, .filtros input { width: 100%; min-width: 0; }
|
||||||
|
#f-busca { grid-column: span 2; }
|
||||||
|
.stat-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 14px; margin-bottom: 18px; }
|
||||||
.tile {
|
.tile {
|
||||||
background: var(--surface); border: 1px solid var(--border); border-radius: 12px;
|
position: relative;
|
||||||
padding: 14px 16px; box-shadow: var(--shadow);
|
overflow: hidden;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 16px;
|
||||||
|
box-shadow: var(--shadow-soft);
|
||||||
}
|
}
|
||||||
.tile .valor { font-size: 26px; font-weight: 700; }
|
.tile::after {
|
||||||
.tile .rotulo { font-size: 12.5px; color: var(--ink-2); margin-top: 2px; }
|
content: "";
|
||||||
.tile .detalhe { font-size: 12px; color: var(--muted); }
|
position: absolute;
|
||||||
|
inset: auto -20px -28px auto;
|
||||||
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||||
|
}
|
||||||
|
.tile .valor { font-size: 29px; font-weight: 900; letter-spacing: -0.04em; }
|
||||||
|
.tile .rotulo { color: var(--ink-2); font-size: 12.5px; font-weight: 750; margin-top: 2px; }
|
||||||
|
.tile .detalhe { color: var(--muted); font-size: 12px; }
|
||||||
.tile.t-good .valor { color: var(--good-text); }
|
.tile.t-good .valor { color: var(--good-text); }
|
||||||
.tile.t-warn .valor { color: var(--ink); }
|
|
||||||
.tile.tile-wide { grid-column: span 2; }
|
.tile.tile-wide { grid-column: span 2; }
|
||||||
@media (max-width: 640px) { .tile.tile-wide { grid-column: span 1; } }
|
.meta-input { width: 78px; text-align: right; padding: 5px 7px; }
|
||||||
.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 ---------- */
|
.ranking, .funil { display: flex; flex-direction: column; gap: 8px; margin-top: 6px; }
|
||||||
.funil { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }
|
.rank-row, .funil-etapa {
|
||||||
.funil-etapa { display: grid; grid-template-columns: 190px 1fr 70px; align-items: center; gap: 8px; padding: 1px 4px; }
|
display: grid;
|
||||||
.funil-etapa.pendente { opacity: 0.4; }
|
grid-template-columns: 150px 1fr 70px;
|
||||||
.funil-label { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
align-items: center;
|
||||||
.funil-barra { height: 14px; border-radius: 4px; overflow: hidden; background: none; }
|
gap: 9px;
|
||||||
.funil-fill { height: 100%; background: var(--bar); border-radius: 0 4px 4px 0; min-width: 2px; }
|
padding: 4px 6px;
|
||||||
.funil-valor { font-size: 12.5px; color: var(--ink-2); text-align: right; font-variant-numeric: tabular-nums; }
|
border-radius: 10px;
|
||||||
|
}
|
||||||
/* barras de ranking: magnitude = um matiz (azul), rótulo direto, sem legenda */
|
.funil-etapa { grid-template-columns: 190px 1fr 70px; }
|
||||||
.ranking { display: flex; flex-direction: column; gap: 7px; }
|
.rank-row { cursor: pointer; }
|
||||||
.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, .oportunidade-clicavel:hover { background: var(--surface-2); }
|
||||||
.rank-row:hover { background: var(--grid); }
|
.rank-row.ativo, .oportunidade-clicavel.ativo { background: color-mix(in srgb, var(--accent) 13%, var(--surface)); font-weight: 800; }
|
||||||
.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 { cursor: default; }
|
||||||
.rank-row.nao-clicavel:hover { background: none; }
|
.rank-row.nao-clicavel:hover { background: transparent; }
|
||||||
.oportunidade-clicavel { cursor: pointer; border-radius: 8px; padding: 6px 8px; }
|
.funil-etapa.pendente { opacity: 0.43; }
|
||||||
.oportunidade-clicavel:hover { background: var(--grid); }
|
.rank-label, .funil-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
|
||||||
.oportunidade-clicavel.ativo { background: color-mix(in srgb, var(--accent) 16%, transparent); }
|
.rank-track, .funil-barra { height: 12px; overflow: hidden; border-radius: 999px; background: var(--grid); }
|
||||||
.rank-label { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
.rank-fill, .funil-fill { height: 100%; min-width: 3px; border-radius: 999px; background: linear-gradient(90deg, var(--bar), #ffb36d); }
|
||||||
.rank-track { height: 14px; border-radius: 4px; overflow: hidden; background: none; }
|
.rank-value, .funil-valor { color: var(--ink-2); text-align: right; font-size: 12.5px; font-variant-numeric: tabular-nums; }
|
||||||
.rank-fill { height: 100%; background: var(--bar); border-radius: 0 4px 4px 0; min-width: 2px; }
|
.oportunidade-clicavel { cursor: pointer; border-radius: 12px; padding: 8px 10px; }
|
||||||
.rank-value { font-size: 12.5px; color: var(--ink-2); text-align: right; font-variant-numeric: tabular-nums; }
|
|
||||||
|
|
||||||
/* ---------- tabela ---------- */
|
/* tabela */
|
||||||
.table-wrap { overflow-x: auto; margin: 0 -4px; }
|
.table-wrap { overflow-x: auto; margin: 0 -6px; }
|
||||||
table { border-collapse: collapse; width: 100%; }
|
table { width: 100%; border-collapse: separate; border-spacing: 0; }
|
||||||
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--grid); white-space: nowrap; }
|
th, td { text-align: left; white-space: nowrap; padding: 10px 12px; border-bottom: 1px solid var(--grid); }
|
||||||
th { font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; color: var(--muted); }
|
th {
|
||||||
|
color: var(--muted);
|
||||||
|
background: var(--surface);
|
||||||
|
font-size: 11px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
}
|
||||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||||
|
.acao-col {
|
||||||
|
position: sticky;
|
||||||
|
left: 0;
|
||||||
|
z-index: 3;
|
||||||
|
width: 58px;
|
||||||
|
min-width: 58px;
|
||||||
|
text-align: center;
|
||||||
|
background: var(--surface);
|
||||||
|
box-shadow: 10px 0 18px -18px rgba(22, 32, 51, 0.8);
|
||||||
|
}
|
||||||
|
td.acao-col { padding-left: 8px; padding-right: 8px; }
|
||||||
tbody tr { cursor: pointer; }
|
tbody tr { cursor: pointer; }
|
||||||
tbody tr:hover { background: color-mix(in srgb, var(--accent) 6%, transparent); }
|
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; }
|
tbody tr:hover .acao-col { background: color-mix(in srgb, var(--accent) 6%, var(--surface)); }
|
||||||
/* Escala sequencial ordinal (excelente -> muito baixo), verde -> ambar -> vermelho,
|
.badge { display: inline-flex; align-items: center; border-radius: 999px; padding: 3px 9px; font-size: 12px; font-weight: 850; white-space: nowrap; }
|
||||||
construida so com os tokens ja validados (--good/--warning/--critical). */
|
.badge.excelente { background: color-mix(in srgb, var(--good) 18%, transparent); color: var(--good-text); }
|
||||||
.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.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.medio { background: color-mix(in srgb, var(--warning) 20%, transparent); color: var(--ink); }
|
||||||
.badge.baixo { background: color-mix(in srgb, var(--warning) 18%, var(--critical) 12%); color: var(--critical); }
|
.badge.baixo { background: color-mix(in srgb, var(--warning) 16%, var(--critical) 10%); color: var(--critical); }
|
||||||
.badge.muito_baixo { background: color-mix(in srgb, var(--critical) 16%, transparent); color: var(--critical); }
|
.badge.muito_baixo { background: color-mix(in srgb, var(--critical) 14%, transparent); color: var(--critical); }
|
||||||
|
.badge.prioridade-1 { background: color-mix(in srgb, var(--good) 18%, transparent); color: var(--good-text); }
|
||||||
.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) 20%, transparent); color: var(--ink); }
|
||||||
.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-3 { background: var(--grid); color: var(--ink-2); }
|
||||||
.badge.prioridade-4 { background: var(--grid); color: var(--muted); }
|
.badge.prioridade-4 { background: var(--grid); color: var(--muted); }
|
||||||
|
|
||||||
.produto-cell { font-size: 12.5px; }
|
.produto-cell { font-size: 12.5px; }
|
||||||
.estrelas { color: var(--warning); letter-spacing: 1px; white-space: nowrap; }
|
.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; }
|
.empresa-cell { max-width: 280px; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.whatsapp-action {
|
||||||
/* ---------- explicacao de score (v2.1) ---------- */
|
width: 32px;
|
||||||
.score-breakdown-wrap { border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; margin-top: 12px; }
|
height: 32px;
|
||||||
.score-breakdown { list-style: none; margin: 6px 0 0; padding: 0; display: flex; flex-direction: column; gap: 3px; font-size: 13px; }
|
display: inline-grid;
|
||||||
.score-breakdown li.ok { color: var(--ink); }
|
place-items: center;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--good) 35%, var(--grid));
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--good) 12%, var(--surface));
|
||||||
|
color: var(--good-text);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 17px;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
.whatsapp-action:hover { background: var(--good); color: #fff; }
|
||||||
|
.pontos-fortes, .score-breakdown { list-style: none; margin: 7px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; font-size: 13px; }
|
||||||
|
.resumo-comercial, .score-breakdown-wrap { border: 1px solid var(--border); border-radius: var(--radius); padding: 13px 14px; margin-top: 12px; background: var(--surface-2); }
|
||||||
|
.resumo-comercial h3 { margin: 0 0 8px; font-size: 14px; }
|
||||||
.score-breakdown li.nok { color: var(--muted); }
|
.score-breakdown li.nok { color: var(--muted); }
|
||||||
|
|
||||||
/* ---------- atalhos de exportacao (v2.1) ---------- */
|
/* usuarios */
|
||||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 12px; }
|
#lista-usuarios { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px; }
|
||||||
.chip {
|
#lista-usuarios > div { padding: 10px 12px; border: 1px solid var(--border); border-radius: 12px; background: var(--surface-2); }
|
||||||
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 ---------- */
|
/* modais e toast */
|
||||||
dialog {
|
dialog {
|
||||||
border: 1px solid var(--border); border-radius: 14px;
|
width: calc(100vw - 40px);
|
||||||
background: var(--surface); color: var(--ink);
|
max-width: 600px;
|
||||||
max-width: 560px; width: calc(100vw - 40px);
|
|
||||||
padding: 0;
|
padding: 0;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--ink);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
}
|
}
|
||||||
dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
|
dialog::backdrop { background: rgba(8, 13, 22, 0.58); backdrop-filter: blur(4px); }
|
||||||
.modal-body { padding: 20px 22px; }
|
.modal-body { padding: 24px; }
|
||||||
.modal-body h2 { margin-top: 0; }
|
.modal-body h2 { margin-top: 0; letter-spacing: -0.03em; }
|
||||||
#modal-historico { max-width: 620px; }
|
#modal-historico { max-width: 680px; }
|
||||||
#modal-historico .lista { max-height: 60vh; overflow-y: auto; margin-top: 10px; }
|
#modal-historico .lista { max-height: 60vh; overflow-y: auto; margin-top: 10px; }
|
||||||
textarea { width: 100%; resize: vertical; }
|
|
||||||
|
|
||||||
.toast {
|
.toast {
|
||||||
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
|
position: fixed;
|
||||||
background: var(--ink); color: var(--page);
|
left: 50%;
|
||||||
padding: 10px 18px; border-radius: 10px; font-weight: 600;
|
bottom: 24px;
|
||||||
z-index: 100; max-width: 80vw;
|
z-index: 100;
|
||||||
|
max-width: min(86vw, 680px);
|
||||||
|
transform: translateX(-50%);
|
||||||
|
padding: 11px 16px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--ink);
|
||||||
|
color: var(--page);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
font-weight: 800;
|
||||||
}
|
}
|
||||||
.hidden { display: none !important; }
|
.hidden { display: none !important; }
|
||||||
.muted { color: var(--muted); font-weight: 400; }
|
.muted { color: var(--muted); font-weight: 400; }
|
||||||
|
.detalhe-grid { display: grid; grid-template-columns: 150px 1fr; gap: 6px 14px; font-size: 13.5px; }
|
||||||
/* 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 dt { color: var(--muted); }
|
||||||
.detalhe-grid dd { margin: 0; word-break: break-word; }
|
.detalhe-grid dd { margin: 0; word-break: break-word; }
|
||||||
|
|
||||||
|
@media (max-width: 1100px) {
|
||||||
|
.grid-3 { grid-template-columns: 1fr 1fr; }
|
||||||
|
.topbar { grid-template-columns: 1fr auto auto auto; }
|
||||||
|
.tabs { grid-column: 1 / -1; order: 2; width: 100%; justify-content: center; }
|
||||||
|
#usuario-logado { justify-self: end; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 780px) {
|
||||||
|
main { padding: 16px 12px 50px; }
|
||||||
|
.topbar { padding: 10px 12px; grid-template-columns: 1fr auto auto; gap: 8px; }
|
||||||
|
.brand-name { display: none; }
|
||||||
|
#usuario-logado { display: none; }
|
||||||
|
.tabs { overflow-x: auto; justify-content: flex-start; }
|
||||||
|
.tab { white-space: nowrap; }
|
||||||
|
.grid-3 { grid-template-columns: 1fr; }
|
||||||
|
.card { border-radius: var(--radius); padding: 16px; }
|
||||||
|
.settings-header, .settings-principal { grid-template-columns: 1fr; }
|
||||||
|
.settings-controls { justify-content: flex-start; }
|
||||||
|
.manual-send-card, #manual-oficial-campos { grid-template-columns: 1fr; }
|
||||||
|
.settings-section input[type="text"],
|
||||||
|
.settings-section input[type="password"],
|
||||||
|
.settings-section textarea,
|
||||||
|
.settings-section select,
|
||||||
|
.manual-send-card input,
|
||||||
|
.manual-send-card select { width: 100%; min-width: 0; }
|
||||||
|
.manual-actions { align-items: stretch; flex-direction: column; }
|
||||||
|
.manual-actions .btn { width: 100%; }
|
||||||
|
#f-busca, .tile.tile-wide { grid-column: span 1; }
|
||||||
|
.rank-row, .funil-etapa { grid-template-columns: 1fr 90px; }
|
||||||
|
.rank-track, .funil-barra { grid-column: 1 / -1; order: 3; }
|
||||||
|
th { top: 107px; }
|
||||||
|
.modal-body { padding: 18px; }
|
||||||
|
}
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
+135
-10
@@ -5,12 +5,12 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>GTI Máquina Comercial</title>
|
<title>GTI Máquina Comercial</title>
|
||||||
<link rel="stylesheet" href="/css/app.css">
|
<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>">
|
<link rel="icon" href="/img/logo-gti.png">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
<div class="brand">
|
<div class="brand">
|
||||||
<span class="brand-mark">GTI</span>
|
<img class="brand-mark" src="/img/logo-gti.png" alt="GTI">
|
||||||
<span class="brand-name">Máquina Comercial</span>
|
<span class="brand-name">Máquina Comercial</span>
|
||||||
</div>
|
</div>
|
||||||
<nav class="tabs" role="tablist">
|
<nav class="tabs" role="tablist">
|
||||||
@@ -206,7 +206,7 @@
|
|||||||
<table id="tabela-leads">
|
<table id="tabela-leads">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Empresa</th><th>WhatsApp</th><th>Cidade</th><th>Nicho</th>
|
<th class="acao-col">Ação</th><th>Empresa</th><th>WhatsApp</th><th>Cidade</th><th>Nicho</th>
|
||||||
<th>Prioridade</th><th class="num">Geral</th>
|
<th>Prioridade</th><th class="num">Geral</th>
|
||||||
<th>Classificação</th><th>Produto</th><th>Exportado</th>
|
<th>Classificação</th><th>Produto</th><th>Exportado</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -283,9 +283,131 @@
|
|||||||
<!-- Modal de configurações -->
|
<!-- Modal de configurações -->
|
||||||
<dialog id="modal-settings">
|
<dialog id="modal-settings">
|
||||||
<form method="dialog" class="modal-body">
|
<form method="dialog" class="modal-body">
|
||||||
<h2>Configurações</h2>
|
<div class="settings-header">
|
||||||
<div class="field">
|
<div>
|
||||||
<label>Padrões Z-PRO (usados nas exportações)</label>
|
<h2>Configurações</h2>
|
||||||
|
<p class="muted">Ajustes de envio, credenciais Z-PRO e preferências comerciais.</p>
|
||||||
|
</div>
|
||||||
|
<span class="chip" id="outreach-status"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="settings-card settings-principal">
|
||||||
|
<div>
|
||||||
|
<label class="settings-title">Envio WhatsApp</label>
|
||||||
|
<p class="muted">O limite vale para envios manuais e automáticos feitos hoje.</p>
|
||||||
|
</div>
|
||||||
|
<div class="settings-controls">
|
||||||
|
<label class="toggle"><input type="checkbox" id="outreach-ativo"> Automação ativa</label>
|
||||||
|
<label>Limite por dia <input type="number" id="outreach-limite" min="1"></label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<details class="settings-section" open>
|
||||||
|
<summary>Enviar mensagem manual</summary>
|
||||||
|
<p class="muted">Cria ou reutiliza um ticket no painel Z-PRO e respeita o limite diário.</p>
|
||||||
|
<div class="manual-send-card">
|
||||||
|
<label class="full">Número do WhatsApp
|
||||||
|
<input type="text" id="manual-numero" placeholder="5511999999999" inputmode="numeric">
|
||||||
|
</label>
|
||||||
|
<div class="manual-channel full" aria-label="Canal de envio manual">
|
||||||
|
<label class="radio"><input type="radio" name="manual-canal" id="manual-canal-naooficial" value="nao_oficial" checked> Não-oficial (texto livre)</label>
|
||||||
|
<label class="radio"><input type="radio" name="manual-canal" id="manual-canal-oficial" value="oficial"> Oficial (Meta, template aprovado)</label>
|
||||||
|
</div>
|
||||||
|
<label class="full" id="manual-mensagem-wrap">Mensagem
|
||||||
|
<textarea id="manual-mensagem" rows="2" placeholder="Digite a mensagem de texto livre..."></textarea>
|
||||||
|
</label>
|
||||||
|
<div id="manual-oficial-campos" class="hidden full">
|
||||||
|
<label class="full">Escolher modelo salvo
|
||||||
|
<select id="manual-template-biblioteca">
|
||||||
|
<option value="">Selecione um template...</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div class="row full">
|
||||||
|
<button class="btn-ghost btn-sm" id="btn-testar-template-biblioteca" type="button">Testar modelo selecionado</button>
|
||||||
|
<span class="muted">Usa o número informado acima e variáveis de exemplo.</span>
|
||||||
|
</div>
|
||||||
|
<label>Template aprovado
|
||||||
|
<input type="text" id="manual-template-nome" placeholder="ex.: confirma_suporte">
|
||||||
|
</label>
|
||||||
|
<label>Idioma
|
||||||
|
<input type="text" id="manual-template-idioma" value="pt_BR">
|
||||||
|
</label>
|
||||||
|
<label>Rota Z-PRO
|
||||||
|
<select id="manual-template-rota">
|
||||||
|
<option value="template">Template padrão</option>
|
||||||
|
<option value="templateBody">Utility/Body</option>
|
||||||
|
<option value="templateMarketingBody">Marketing/Body</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div class="template-vars full">
|
||||||
|
<label>Variáveis do template</label>
|
||||||
|
<p class="muted">Preencha na mesma ordem do template: {{1}}, {{2}}, {{3}}...</p>
|
||||||
|
<div class="variable-helper">
|
||||||
|
<select id="manual-variable-picker">
|
||||||
|
<option value="">Inserir variável da Máquina Comercial...</option>
|
||||||
|
</select>
|
||||||
|
<span class="muted">Clique em um campo abaixo e escolha uma variável.</span>
|
||||||
|
</div>
|
||||||
|
<div class="template-vars-grid">
|
||||||
|
<label class="template-var-field">Variável {{1}} <input type="text" class="manual-template-var" id="manual-template-var1" data-var-index="1" placeholder="Ex.: Gustavo"></label>
|
||||||
|
<label class="template-var-field">Variável {{2}} <input type="text" class="manual-template-var" data-var-index="2" placeholder="Ex.: Suporte GLPI #123"></label>
|
||||||
|
<label class="template-var-field">Variável {{3}} <input type="text" class="manual-template-var" data-var-index="3"></label>
|
||||||
|
<label class="template-var-field">Variável {{4}} <input type="text" class="manual-template-var" data-var-index="4"></label>
|
||||||
|
<label class="template-var-field">Variável {{5}} <input type="text" class="manual-template-var" data-var-index="5"></label>
|
||||||
|
</div>
|
||||||
|
<div class="template-preview" id="manual-template-preview">Selecione um template para ver a pré-visualização.</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="manual-actions full">
|
||||||
|
<span class="muted" id="manual-status"></span>
|
||||||
|
<button class="btn btn-primary" id="btn-enviar-manual" type="button">Enviar mensagem</button>
|
||||||
|
</div>
|
||||||
|
<button class="btn-ghost btn-sm" id="btn-toggle-outreach-log" type="button">Ver log de envios</button>
|
||||||
|
<div id="outreach-ultimos" class="lista hidden full"></div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details class="settings-section">
|
||||||
|
<summary>Templates automáticos</summary>
|
||||||
|
<p class="muted">Mensagens usadas quando a automação estiver ativada. Uma por produto recomendado.</p>
|
||||||
|
<div class="template-sync-inline">
|
||||||
|
<span class="muted" id="waba-template-library-status">Carregando biblioteca de templates...</span>
|
||||||
|
<button class="btn-ghost btn-sm" id="btn-sync-gchat-templates-inline" type="button">Atualizar lista do GChat</button>
|
||||||
|
</div>
|
||||||
|
<div id="outreach-templates" class="lista"></div>
|
||||||
|
<div class="row space-between">
|
||||||
|
<span></span>
|
||||||
|
<button class="btn-ghost" id="btn-salvar-outreach" type="button">Salvar templates</button>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details class="settings-section">
|
||||||
|
<summary>Credenciais Z-PRO</summary>
|
||||||
|
<p class="muted">Use os dados de Admin > API do Z-PRO. Pode colar a Base URL com ou sem <code>https://</code>.</p>
|
||||||
|
<div class="row">
|
||||||
|
<label>Base URL <input type="text" id="cfg-zpro-baseurl" placeholder="seu-dominio-zpro.com.br"></label>
|
||||||
|
<label>API ID <input type="text" id="cfg-zpro-apiid"></label>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<label>Token <input type="password" id="cfg-zpro-token" autocomplete="off"></label>
|
||||||
|
<label>WhatsApp ID <input type="text" id="cfg-zpro-whatsappid"></label>
|
||||||
|
</div>
|
||||||
|
<div class="row space-between">
|
||||||
|
<span class="muted" id="zpro-credenciais-status"></span>
|
||||||
|
<button class="btn-ghost" id="btn-testar-zpro" type="button">Testar conexão</button>
|
||||||
|
</div>
|
||||||
|
<div class="template-sync-box">
|
||||||
|
<label>URL de templates do GChat <input type="text" id="cfg-gchat-templates-url" placeholder="https://apigchat.gtigrupo.com.br/...templates..."></label>
|
||||||
|
<label>Token GChat opcional <input type="password" id="cfg-gchat-token" autocomplete="off"></label>
|
||||||
|
<div class="row space-between">
|
||||||
|
<span class="muted" id="gchat-template-sync-status"></span>
|
||||||
|
<button class="btn-ghost" id="btn-sync-gchat-templates" type="button">Sincronizar templates</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details class="settings-section">
|
||||||
|
<summary>Padrões de exportação e ticket</summary>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<label>Pipeline <input type="number" id="cfg-pipeline" min="1"></label>
|
<label>Pipeline <input type="number" id="cfg-pipeline" min="1"></label>
|
||||||
<label>Etapa <input type="number" id="cfg-stage" min="1"></label>
|
<label>Etapa <input type="number" id="cfg-stage" min="1"></label>
|
||||||
@@ -293,13 +415,15 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<label>Previsão de fechamento (dias) <input type="number" id="cfg-forecast" min="1"></label>
|
<label>Previsão de fechamento (dias) <input type="number" id="cfg-forecast" min="1"></label>
|
||||||
|
<label>Fila ticket manual <input type="number" id="cfg-ticket-queue" min="1"></label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</details>
|
||||||
<div class="field zona-risco">
|
|
||||||
<label>Zona de risco</label>
|
<details class="settings-section zona-risco">
|
||||||
|
<summary>Zona de risco</summary>
|
||||||
<p class="muted">Apaga permanentemente todos os leads, exportações, capturas e extrações. Configurações e nichos não são afetados.</p>
|
<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>
|
<button class="btn-danger" id="btn-limpar-base" type="button">🗑️ Limpar toda a base de leads</button>
|
||||||
</div>
|
</details>
|
||||||
<div class="row space-between">
|
<div class="row space-between">
|
||||||
<button class="btn-ghost" value="cancel">Fechar</button>
|
<button class="btn-ghost" value="cancel">Fechar</button>
|
||||||
<button class="btn btn-primary" id="btn-salvar-settings" value="default">Salvar</button>
|
<button class="btn btn-primary" id="btn-salvar-settings" value="default">Salvar</button>
|
||||||
@@ -315,6 +439,7 @@
|
|||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Senha de segurança <input type="password" id="reset-base-senha" autocomplete="off"></label>
|
<label>Senha de segurança <input type="password" id="reset-base-senha" autocomplete="off"></label>
|
||||||
</div>
|
</div>
|
||||||
|
<p class="muted erro hidden" id="reset-base-erro"></p>
|
||||||
<div class="row space-between">
|
<div class="row space-between">
|
||||||
<button class="btn-ghost" id="btn-cancelar-reset-base" type="button">Cancelar</button>
|
<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>
|
<button class="btn-danger" id="btn-confirmar-reset-base" type="button">Confirmar limpeza</button>
|
||||||
|
|||||||
@@ -79,6 +79,11 @@ function h(tag, attrs = {}, ...children) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let toastTimer = null;
|
let toastTimer = null;
|
||||||
|
// Aviso: um <dialog> aberto via showModal() fica acima de qualquer div normal
|
||||||
|
// (top layer do navegador, z-index nao ajuda — e testamos que nem a Popover
|
||||||
|
// API resolve, o dialog continua por cima). Por isso o toast NAO deve ser a
|
||||||
|
// unica forma de mostrar erro de uma acao disparada de dentro de um modal
|
||||||
|
// aberto: use tambem uma mensagem inline no proprio modal nesses casos.
|
||||||
function toast(message, ms = 3500) {
|
function toast(message, ms = 3500) {
|
||||||
const box = el('toast');
|
const box = el('toast');
|
||||||
box.textContent = message;
|
box.textContent = message;
|
||||||
|
|||||||
+550
-3
@@ -68,15 +68,543 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// configurações
|
// configurações
|
||||||
|
let WABA_TEMPLATE_LIBRARY = [];
|
||||||
|
let COMMERCIAL_VARIABLES = [];
|
||||||
|
let focusedVariableInput = null;
|
||||||
|
let manualLeadContext = null;
|
||||||
|
|
||||||
|
async function carregarVariaveisComerciais() {
|
||||||
|
const { variables } = await API.get('/api/outreach/variables');
|
||||||
|
COMMERCIAL_VARIABLES = variables || [];
|
||||||
|
const picker = el('manual-variable-picker');
|
||||||
|
if (picker) {
|
||||||
|
picker.replaceChildren(
|
||||||
|
h('option', { value: '' }, 'Inserir variável da Máquina Comercial...'),
|
||||||
|
...COMMERCIAL_VARIABLES.map((variable) => h('option', { value: `{{${variable.key}}}` }, `{{${variable.key}}} - ${variable.label}`))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function carregarBibliotecaWaba() {
|
||||||
|
const { templates, lastSync } = await API.get('/api/outreach/waba-templates');
|
||||||
|
WABA_TEMPLATE_LIBRARY = templates || [];
|
||||||
|
const select = el('manual-template-biblioteca');
|
||||||
|
if (select) select.replaceChildren(...templateOptions(select.value));
|
||||||
|
const statusEl = el('waba-template-library-status');
|
||||||
|
if (statusEl) {
|
||||||
|
statusEl.textContent = lastSync
|
||||||
|
? `${WABA_TEMPLATE_LIBRARY.length} templates carregados. Última atualização: ${dataBr(lastSync)}`
|
||||||
|
: `${WABA_TEMPLATE_LIBRARY.length} templates locais carregados. Para trazer todos do GChat, preencha o Token GChat e clique em Atualizar.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateLabel(template) {
|
||||||
|
return `${template.name} (${template.language})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateOptions(selected = '') {
|
||||||
|
return [h('option', { value: '' }, 'Selecione um template...')].concat(
|
||||||
|
WABA_TEMPLATE_LIBRARY.map((template) => h('option', {
|
||||||
|
value: template.name,
|
||||||
|
selected: template.name === selected ? '' : null
|
||||||
|
}, templateLabel(template)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function preencherVariaveis(inputs, variables, fallback = []) {
|
||||||
|
inputs.forEach((input, index) => {
|
||||||
|
input.value = variables[index] || fallback[index] || '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateVariableCount(template) {
|
||||||
|
if (!template) return 0;
|
||||||
|
const fromVariables = Array.isArray(template.variables) ? template.variables.length : 0;
|
||||||
|
const matches = String(template.text || '').match(/{{\s*\d+\s*}}/g) || [];
|
||||||
|
const fromText = Math.max(0, ...matches.map((match) => Number(match.replace(/\D/g, ''))));
|
||||||
|
return Math.min(5, Math.max(fromVariables, fromText));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setVariableFields(container, template, inputs, fallback = []) {
|
||||||
|
const count = templateVariableCount(template);
|
||||||
|
inputs.forEach((input, index) => {
|
||||||
|
const field = input.closest('.template-var-field') || input.closest('label');
|
||||||
|
const visible = index < count;
|
||||||
|
if (field) field.classList.toggle('hidden', !visible);
|
||||||
|
if (!visible) input.value = '';
|
||||||
|
else if (!input.value) input.value = template?.variables?.[index] || fallback[index] || '';
|
||||||
|
});
|
||||||
|
const empty = container?.querySelector?.('.template-vars-empty');
|
||||||
|
if (empty) empty.classList.toggle('hidden', count > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewTemplateText(template, inputs) {
|
||||||
|
const text = String(template?.text || '').trim();
|
||||||
|
if (!template) return 'Selecione um template para ver a pré-visualização.';
|
||||||
|
if (!text) return 'Pré-visualização indisponível para este template local.';
|
||||||
|
return text.replace(/{{\s*(\d+)\s*}}/g, (_, index) => {
|
||||||
|
const input = inputs[Number(index) - 1];
|
||||||
|
const value = resolverVariavelManual(input?.value?.trim());
|
||||||
|
return value ? `[${value}]` : `[Variável ${index}]`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function atualizarPreview(previewEl, template, inputs) {
|
||||||
|
if (previewEl) previewEl.textContent = previewTemplateText(template, inputs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectVisibleVariables(inputs) {
|
||||||
|
return inputs
|
||||||
|
.filter((input) => !(input.closest('.template-var-field') || input.closest('label'))?.classList.contains('hidden'))
|
||||||
|
.map((input) => input.value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectVisibleVariablesResolvidas(inputs) {
|
||||||
|
return collectVisibleVariables(inputs).map(resolverVariavelManual);
|
||||||
|
}
|
||||||
|
|
||||||
|
function valoresVariaveisManuais(lead = manualLeadContext) {
|
||||||
|
const empresa = lead?.empresa || lead?.legal_name || lead?.businessName || lead?.name || 'Empresa Teste';
|
||||||
|
const produto = lead?.produto || lead?.produto_principal || lead?.interesse || 'Atendimento comercial';
|
||||||
|
const segmento = lead?.segmento_label || lead?.segmento || 'Suporte';
|
||||||
|
const name = lead?.name || empresa;
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
empresa,
|
||||||
|
businessName: empresa,
|
||||||
|
firstName: String(name).split(/\s+/).filter(Boolean)[0] || empresa,
|
||||||
|
lastName: lead?.lastName || '',
|
||||||
|
produto,
|
||||||
|
protocol: lead?.protocol || produto,
|
||||||
|
cidade: lead?.cidade || 'Salvador',
|
||||||
|
uf: lead?.uf || 'BA',
|
||||||
|
segmento,
|
||||||
|
cnpj: lead?.cnpj || '00.000.000/0001-00',
|
||||||
|
email: lead?.email || 'cliente@exemplo.com.br',
|
||||||
|
phoneNumber: lead?.whatsapp || '5575999091780',
|
||||||
|
whatsapp: lead?.whatsapp || '5575999091780',
|
||||||
|
kanban: lead?.kanban || produto,
|
||||||
|
user: lead?.user || 'Grupo GTI',
|
||||||
|
userEmail: lead?.userEmail || 'comercial@gtigrupo.com.br',
|
||||||
|
greeting: 'Olá'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolverVariavelManual(value) {
|
||||||
|
const values = valoresVariaveisManuais();
|
||||||
|
let output = String(value || 'Informação')
|
||||||
|
.replaceAll('{empresa}', values.empresa)
|
||||||
|
.replaceAll('{produto}', values.produto)
|
||||||
|
.replaceAll('{cidade}', values.cidade)
|
||||||
|
.replaceAll('{segmento}', values.segmento);
|
||||||
|
for (const [key, variableValue] of Object.entries(values)) {
|
||||||
|
output = output.replaceAll(`{{${key}}}`, variableValue);
|
||||||
|
}
|
||||||
|
for (const variable of COMMERCIAL_VARIABLES) {
|
||||||
|
if (!output.includes(`{{${variable.key}}}`)) continue;
|
||||||
|
output = output.replaceAll(`{{${variable.key}}}`, values[variable.key] || variable.label);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
const variavelExemplo = resolverVariavelManual;
|
||||||
|
|
||||||
|
function missingVisibleVariables(inputs) {
|
||||||
|
return inputs
|
||||||
|
.filter((input) => !(input.closest('.template-var-field') || input.closest('label'))?.classList.contains('hidden'))
|
||||||
|
.filter((input) => !input.value.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function aplicarTemplateBiblioteca(template, { nomeEl, idiomaEl, routeEl, variableInputs }) {
|
||||||
|
if (!template) return;
|
||||||
|
nomeEl.value = template.name;
|
||||||
|
idiomaEl.value = template.language;
|
||||||
|
if (routeEl) routeEl.value = template.route;
|
||||||
|
preencherVariaveis(variableInputs, template.variables);
|
||||||
|
}
|
||||||
|
|
||||||
|
function variablePickerEl() {
|
||||||
|
return h('select', { class: 'variable-picker' },
|
||||||
|
h('option', { value: '' }, 'Inserir variável da Máquina Comercial...'),
|
||||||
|
...COMMERCIAL_VARIABLES.map((variable) => h('option', { value: `{{${variable.key}}}` }, `{{${variable.key}}} - ${variable.label}`))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function carregarOutreach() {
|
||||||
|
const { settings } = await API.get('/api/settings');
|
||||||
|
el('outreach-ativo').checked = settings['outreach.ativo'] === 'true';
|
||||||
|
el('outreach-limite').value = settings['outreach.mensagensPorDia'] || 10;
|
||||||
|
|
||||||
|
const [{ templates }, status] = await Promise.all([
|
||||||
|
API.get('/api/outreach/templates'),
|
||||||
|
API.get('/api/outreach/status')
|
||||||
|
]);
|
||||||
|
el('outreach-status').textContent = `Enviado hoje: ${status.enviadosHoje}/${status.mensagensPorDia}`;
|
||||||
|
|
||||||
|
el('outreach-templates').replaceChildren(...templates.map((t) => {
|
||||||
|
const oficial = t.canal === 'oficial';
|
||||||
|
const mensagemEl = h('textarea', {
|
||||||
|
class: 'outreach-template-mensagem', rows: 2,
|
||||||
|
style: oficial ? 'display:none' : ''
|
||||||
|
}, t.mensagem);
|
||||||
|
const nomeEl = h('input', { type: 'text', class: 'outreach-template-waba-nome', value: t.template_waba_nome || '' });
|
||||||
|
const idiomaEl = h('input', { type: 'text', class: 'outreach-template-waba-idioma', value: t.template_waba_idioma || 'pt_BR' });
|
||||||
|
let variaveisSalvas = [];
|
||||||
|
try {
|
||||||
|
variaveisSalvas = JSON.parse(t.template_waba_variaveis_json || '[]');
|
||||||
|
} catch {
|
||||||
|
variaveisSalvas = [];
|
||||||
|
}
|
||||||
|
let templateSelecionado = WABA_TEMPLATE_LIBRARY.find((item) => item.name === t.template_waba_nome) || null;
|
||||||
|
const variaveisEls = Array.from({ length: 5 }, (_, index) => {
|
||||||
|
const input = h('input', {
|
||||||
|
type: 'text',
|
||||||
|
class: 'outreach-template-waba-var',
|
||||||
|
value: variaveisSalvas[index] || (index === 0 ? '{empresa}' : index === 1 ? '{produto}' : ''),
|
||||||
|
placeholder: index === 0 ? '{empresa}' : index === 1 ? '{produto}' : ''
|
||||||
|
});
|
||||||
|
input.addEventListener('focus', () => { focusedVariableInput = input; });
|
||||||
|
return h('label', { class: 'template-var-field' }, `Variável {{${index + 1}}}`, input);
|
||||||
|
});
|
||||||
|
const bibliotecaEl = h('select', { class: 'outreach-template-biblioteca' }, ...templateOptions(t.template_waba_nome || ''));
|
||||||
|
const variablePicker = variablePickerEl();
|
||||||
|
const previewEl = h('div', { class: 'template-preview' }, 'Selecione um template para ver a pré-visualização.');
|
||||||
|
variablePicker.addEventListener('change', () => {
|
||||||
|
if (!focusedVariableInput || !oficialEl.contains(focusedVariableInput) || !variablePicker.value) return;
|
||||||
|
focusedVariableInput.value = variablePicker.value;
|
||||||
|
focusedVariableInput.dispatchEvent(new Event('input'));
|
||||||
|
variablePicker.value = '';
|
||||||
|
});
|
||||||
|
bibliotecaEl.addEventListener('change', () => {
|
||||||
|
templateSelecionado = WABA_TEMPLATE_LIBRARY.find((item) => item.name === bibliotecaEl.value);
|
||||||
|
const inputs = Array.from(oficialEl.querySelectorAll('.outreach-template-waba-var'));
|
||||||
|
aplicarTemplateBiblioteca(templateSelecionado, {
|
||||||
|
nomeEl,
|
||||||
|
idiomaEl,
|
||||||
|
variableInputs: inputs
|
||||||
|
});
|
||||||
|
setVariableFields(oficialEl, templateSelecionado, inputs, ['{empresa}', '{produto}']);
|
||||||
|
atualizarPreview(previewEl, templateSelecionado, inputs);
|
||||||
|
atualizarAviso();
|
||||||
|
});
|
||||||
|
const avisoEl = h('p', { class: 'muted outreach-template-aviso hidden' },
|
||||||
|
'⚠️ Preencha o nome do template pra essa automação funcionar.');
|
||||||
|
const oficialEl = h('div', {
|
||||||
|
class: 'outreach-template-oficial',
|
||||||
|
style: oficial ? '' : 'display:none'
|
||||||
|
},
|
||||||
|
h('label', {}, 'Escolher modelo salvo', bibliotecaEl),
|
||||||
|
h('div', { class: 'row' },
|
||||||
|
h('label', {}, 'Nome do template aprovado', nomeEl),
|
||||||
|
h('label', {}, 'Idioma', idiomaEl)),
|
||||||
|
h('div', { class: 'template-vars outreach-template-vars' },
|
||||||
|
h('label', {}, 'Variáveis automáticas'),
|
||||||
|
h('p', { class: 'muted' }, 'Use placeholders como {empresa}, {produto}, {cidade}, {segmento}.'),
|
||||||
|
h('div', { class: 'variable-helper' },
|
||||||
|
variablePicker,
|
||||||
|
h('span', { class: 'muted' }, 'Clique em um campo abaixo e escolha uma variável.')),
|
||||||
|
h('p', { class: 'muted template-vars-empty hidden' }, 'Este template não exige variáveis.'),
|
||||||
|
h('div', { class: 'template-vars-grid' }, ...variaveisEls),
|
||||||
|
previewEl),
|
||||||
|
h('a', {
|
||||||
|
href: 'https://business.facebook.com/wa/manage/message-templates/',
|
||||||
|
target: '_blank', rel: 'noopener', class: 'outreach-template-link'
|
||||||
|
}, '↗ Ver/criar templates no Meta Business Manager'),
|
||||||
|
avisoEl);
|
||||||
|
|
||||||
|
const atualizarAviso = () => {
|
||||||
|
avisoEl.classList.toggle('hidden', radioOficial.checked ? Boolean(nomeEl.value.trim()) : true);
|
||||||
|
};
|
||||||
|
nomeEl.addEventListener('input', atualizarAviso);
|
||||||
|
for (const input of variaveisEls.map((label) => label.querySelector('input'))) {
|
||||||
|
input.addEventListener('input', () => atualizarPreview(previewEl, templateSelecionado, Array.from(oficialEl.querySelectorAll('.outreach-template-waba-var'))));
|
||||||
|
}
|
||||||
|
|
||||||
|
const radioNaoOficial = h('input', {
|
||||||
|
type: 'radio', name: `canal-${t.produto}`, class: 'outreach-template-canal', value: 'nao_oficial',
|
||||||
|
checked: oficial ? null : ''
|
||||||
|
});
|
||||||
|
const radioOficial = h('input', {
|
||||||
|
type: 'radio', name: `canal-${t.produto}`, class: 'outreach-template-canal', value: 'oficial',
|
||||||
|
checked: oficial ? '' : null
|
||||||
|
});
|
||||||
|
const alternarCanal = () => {
|
||||||
|
const usaOficial = radioOficial.checked;
|
||||||
|
mensagemEl.style.display = usaOficial ? 'none' : '';
|
||||||
|
oficialEl.style.display = usaOficial ? '' : 'none';
|
||||||
|
atualizarAviso();
|
||||||
|
};
|
||||||
|
radioNaoOficial.addEventListener('change', alternarCanal);
|
||||||
|
radioOficial.addEventListener('change', alternarCanal);
|
||||||
|
atualizarAviso();
|
||||||
|
queueMicrotask(() => {
|
||||||
|
const inputs = Array.from(oficialEl.querySelectorAll('.outreach-template-waba-var'));
|
||||||
|
setVariableFields(oficialEl, templateSelecionado, inputs, ['{empresa}', '{produto}']);
|
||||||
|
atualizarPreview(previewEl, templateSelecionado, inputs);
|
||||||
|
});
|
||||||
|
|
||||||
|
return h('div', { class: 'item outreach-template', 'data-produto': t.produto },
|
||||||
|
h('div', { class: 'row space-between' },
|
||||||
|
h('strong', {}, t.produto),
|
||||||
|
h('label', { class: 'radio' },
|
||||||
|
h('input', { type: 'checkbox', class: 'outreach-template-ativo', checked: t.ativo ? '' : null }),
|
||||||
|
' Ativo')),
|
||||||
|
h('div', { class: 'row' },
|
||||||
|
h('label', { class: 'radio' }, radioNaoOficial, ' Não-oficial (texto livre)'),
|
||||||
|
h('label', { class: 'radio' }, radioOficial, ' Oficial (Meta, template aprovado)')),
|
||||||
|
mensagemEl,
|
||||||
|
oficialEl);
|
||||||
|
}));
|
||||||
|
|
||||||
|
el('outreach-ultimos').replaceChildren(...status.ultimos.map((s) => {
|
||||||
|
const quem = s.origem === 'manual' ? (s.numero || 'número avulso') : `${s.empresa || '?'} (${s.cidade || '?'})`;
|
||||||
|
const rotulo = s.origem === 'manual' ? `Manual → ${quem}` : `${s.produto} → ${quem}`;
|
||||||
|
const statusIcone = s.status === 'enviado' ? '✅' : '❌';
|
||||||
|
return h('div', { class: 'item' },
|
||||||
|
h('div', {}, `${statusIcone} ${rotulo}`),
|
||||||
|
h('div', { class: 'sub' }, `${dataBr(s.sent_at)} · canal ${s.canal === 'oficial' ? 'oficial' : 'não-oficial'}${s.erro ? ` · ${s.erro}` : ''}`));
|
||||||
|
}));
|
||||||
|
if (!status.ultimos.length) {
|
||||||
|
el('outreach-ultimos').replaceChildren(h('p', { class: 'muted' }, 'Nenhum envio ainda.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
el('btn-settings').addEventListener('click', async () => {
|
el('btn-settings').addEventListener('click', async () => {
|
||||||
const { settings } = await API.get('/api/settings');
|
const { settings } = await API.get('/api/settings');
|
||||||
el('cfg-pipeline').value = settings['zpro.pipelineId'] || 1;
|
el('cfg-pipeline').value = settings['zpro.pipelineId'] || 1;
|
||||||
el('cfg-stage').value = settings['zpro.stageId'] || 1;
|
el('cfg-stage').value = settings['zpro.stageId'] || 1;
|
||||||
el('cfg-responsible').value = settings['zpro.responsibleId'] || 15;
|
el('cfg-responsible').value = settings['zpro.responsibleId'] || 15;
|
||||||
|
el('cfg-ticket-queue').value = settings['zpro.ticketQueueId'] || 12;
|
||||||
el('cfg-forecast').value = settings['zpro.closingForecastDays'] || 30;
|
el('cfg-forecast').value = settings['zpro.closingForecastDays'] || 30;
|
||||||
|
el('cfg-zpro-baseurl').value = settings['zpro.baseUrl'] || '';
|
||||||
|
el('cfg-zpro-apiid').value = settings['zpro.apiId'] || '';
|
||||||
|
el('cfg-zpro-token').value = settings['zpro.bearerToken'] || '';
|
||||||
|
el('cfg-zpro-whatsappid').value = settings['zpro.whatsappId'] || '';
|
||||||
|
el('cfg-gchat-templates-url').value = settings['gchat.templatesUrl'] || '';
|
||||||
|
el('cfg-gchat-token').value = settings['gchat.bearerToken'] || '';
|
||||||
|
el('zpro-credenciais-status').textContent = '';
|
||||||
el('modal-settings').showModal();
|
el('modal-settings').showModal();
|
||||||
|
try {
|
||||||
|
await carregarBibliotecaWaba();
|
||||||
|
await carregarVariaveisComerciais();
|
||||||
|
await carregarOutreach();
|
||||||
|
} catch (error) {
|
||||||
|
toast(`Erro ao carregar automação: ${error.message}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
el('btn-testar-zpro').addEventListener('click', async () => {
|
||||||
|
const statusEl = el('zpro-credenciais-status');
|
||||||
|
statusEl.textContent = 'Salvando e testando...';
|
||||||
|
try {
|
||||||
|
await API.put('/api/settings', {
|
||||||
|
'zpro.baseUrl': el('cfg-zpro-baseurl').value.trim(),
|
||||||
|
'zpro.apiId': el('cfg-zpro-apiid').value.trim(),
|
||||||
|
'zpro.bearerToken': el('cfg-zpro-token').value.trim(),
|
||||||
|
'zpro.whatsappId': el('cfg-zpro-whatsappid').value.trim(),
|
||||||
|
'gchat.templatesUrl': el('cfg-gchat-templates-url').value.trim(),
|
||||||
|
'gchat.bearerToken': el('cfg-gchat-token').value.trim(),
|
||||||
|
'outreach.ativo': el('outreach-ativo').checked ? 'true' : 'false',
|
||||||
|
'outreach.mensagensPorDia': el('outreach-limite').value
|
||||||
|
});
|
||||||
|
const resultado = await API.post('/api/outreach/testar-conexao');
|
||||||
|
const diag = resultado.diagnostico
|
||||||
|
? `\nBase: ${resultado.diagnostico.baseUrl || '-'} | API ID: ${resultado.diagnostico.apiId || '-'} | Token: ${resultado.diagnostico.token || '-'} | WhatsApp ID: ${resultado.diagnostico.whatsappId || '-'}`
|
||||||
|
: '';
|
||||||
|
statusEl.textContent = resultado.ok ? `✅ Conexão OK${diag}` : `❌ ${resultado.erro}${diag}`;
|
||||||
|
} catch (error) {
|
||||||
|
statusEl.textContent = `❌ ${error.message}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
el('btn-sync-gchat-templates').addEventListener('click', async () => {
|
||||||
|
await sincronizarTemplatesGchat();
|
||||||
|
});
|
||||||
|
|
||||||
|
el('btn-sync-gchat-templates-inline').addEventListener('click', async () => {
|
||||||
|
await sincronizarTemplatesGchat();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function sincronizarTemplatesGchat() {
|
||||||
|
const statusEl = el('gchat-template-sync-status');
|
||||||
|
const inlineStatusEl = el('waba-template-library-status');
|
||||||
|
statusEl.textContent = 'Sincronizando...';
|
||||||
|
if (inlineStatusEl) inlineStatusEl.textContent = 'Sincronizando com GChat...';
|
||||||
|
try {
|
||||||
|
await API.put('/api/settings', {
|
||||||
|
'gchat.templatesUrl': el('cfg-gchat-templates-url').value.trim(),
|
||||||
|
'gchat.bearerToken': el('cfg-gchat-token').value.trim()
|
||||||
|
});
|
||||||
|
const result = await API.post('/api/outreach/waba-templates/sync');
|
||||||
|
statusEl.textContent = result.ok ? `✅ ${result.total} templates sincronizados` : `❌ ${result.erro}`;
|
||||||
|
if (inlineStatusEl) inlineStatusEl.textContent = result.ok
|
||||||
|
? `✅ ${result.total} templates sincronizados do GChat`
|
||||||
|
: `❌ ${result.erro}. Preencha o Token GChat opcional em Credenciais Z-PRO.`;
|
||||||
|
await carregarBibliotecaWaba();
|
||||||
|
await carregarOutreach();
|
||||||
|
} catch (error) {
|
||||||
|
statusEl.textContent = `❌ ${error.message}`;
|
||||||
|
if (inlineStatusEl) inlineStatusEl.textContent = `❌ ${error.message}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
el('btn-salvar-outreach').addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
await API.put('/api/settings', {
|
||||||
|
'outreach.ativo': el('outreach-ativo').checked ? 'true' : 'false',
|
||||||
|
'outreach.mensagensPorDia': el('outreach-limite').value
|
||||||
|
});
|
||||||
|
for (const item of el('outreach-templates').children) {
|
||||||
|
const canalEl = item.querySelector('.outreach-template-canal:checked');
|
||||||
|
await API.put(`/api/outreach/templates/${encodeURIComponent(item.dataset.produto)}`, {
|
||||||
|
mensagem: item.querySelector('.outreach-template-mensagem').value,
|
||||||
|
ativo: item.querySelector('.outreach-template-ativo').checked,
|
||||||
|
canal: canalEl ? canalEl.value : 'nao_oficial',
|
||||||
|
templateWabaNome: item.querySelector('.outreach-template-waba-nome').value,
|
||||||
|
templateWabaIdioma: item.querySelector('.outreach-template-waba-idioma').value,
|
||||||
|
templateWabaVariaveis: collectVisibleVariables(Array.from(item.querySelectorAll('.outreach-template-waba-var')))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await carregarOutreach();
|
||||||
|
toast('Automação salva');
|
||||||
|
} catch (error) {
|
||||||
|
toast(`Erro: ${error.message}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function alternarCanalManual() {
|
||||||
|
const oficial = el('manual-canal-oficial').checked;
|
||||||
|
el('manual-mensagem-wrap').classList.toggle('hidden', oficial);
|
||||||
|
el('manual-oficial-campos').classList.toggle('hidden', !oficial);
|
||||||
|
}
|
||||||
|
el('manual-canal-naooficial').addEventListener('change', alternarCanalManual);
|
||||||
|
el('manual-canal-oficial').addEventListener('change', alternarCanalManual);
|
||||||
|
|
||||||
|
el('manual-template-biblioteca').replaceChildren(...templateOptions());
|
||||||
|
el('manual-template-biblioteca').addEventListener('change', () => {
|
||||||
|
const template = WABA_TEMPLATE_LIBRARY.find((item) => item.name === el('manual-template-biblioteca').value);
|
||||||
|
const inputs = Array.from(document.querySelectorAll('.manual-template-var'));
|
||||||
|
aplicarTemplateBiblioteca(template, {
|
||||||
|
nomeEl: el('manual-template-nome'),
|
||||||
|
idiomaEl: el('manual-template-idioma'),
|
||||||
|
routeEl: el('manual-template-rota'),
|
||||||
|
variableInputs: inputs
|
||||||
|
});
|
||||||
|
setVariableFields(el('manual-oficial-campos'), template, inputs);
|
||||||
|
atualizarPreview(el('manual-template-preview'), template, inputs);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const input of document.querySelectorAll('.manual-template-var')) {
|
||||||
|
input.addEventListener('focus', () => { focusedVariableInput = input; });
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
const template = WABA_TEMPLATE_LIBRARY.find((item) => item.name === el('manual-template-biblioteca').value);
|
||||||
|
atualizarPreview(el('manual-template-preview'), template, Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
el('manual-variable-picker').addEventListener('change', () => {
|
||||||
|
if (!focusedVariableInput || !el('manual-variable-picker').value) return;
|
||||||
|
focusedVariableInput.value = el('manual-variable-picker').value;
|
||||||
|
focusedVariableInput.dispatchEvent(new Event('input'));
|
||||||
|
el('manual-variable-picker').value = '';
|
||||||
|
});
|
||||||
|
setVariableFields(el('manual-oficial-campos'), null, Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
|
||||||
|
el('btn-testar-template-biblioteca').addEventListener('click', async () => {
|
||||||
|
const statusEl = el('manual-status');
|
||||||
|
const template = WABA_TEMPLATE_LIBRARY.find((item) => item.name === el('manual-template-biblioteca').value);
|
||||||
|
const numero = el('manual-numero').value.trim();
|
||||||
|
statusEl.classList.remove('status-ok', 'status-error');
|
||||||
|
if (!template) {
|
||||||
|
statusEl.textContent = '❌ Selecione um modelo salvo primeiro.';
|
||||||
|
statusEl.classList.add('status-error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!numero) {
|
||||||
|
statusEl.textContent = '❌ Informe um número de teste acima.';
|
||||||
|
statusEl.classList.add('status-error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
aplicarTemplateBiblioteca(template, {
|
||||||
|
nomeEl: el('manual-template-nome'),
|
||||||
|
idiomaEl: el('manual-template-idioma'),
|
||||||
|
routeEl: el('manual-template-rota'),
|
||||||
|
variableInputs: Array.from(document.querySelectorAll('.manual-template-var'))
|
||||||
|
});
|
||||||
|
const variaveis = template.variables.map(resolverVariavelManual);
|
||||||
|
preencherVariaveis(Array.from(document.querySelectorAll('.manual-template-var')), variaveis);
|
||||||
|
setVariableFields(el('manual-oficial-campos'), template, Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
atualizarPreview(el('manual-template-preview'), template, Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
statusEl.textContent = `Testando ${template.name}...`;
|
||||||
|
try {
|
||||||
|
const resultado = await API.post('/api/outreach/enviar-manual', {
|
||||||
|
numero,
|
||||||
|
canal: 'oficial',
|
||||||
|
mensagem: '',
|
||||||
|
templateWabaNome: template.name,
|
||||||
|
templateWabaIdioma: template.language,
|
||||||
|
templateRota: template.route,
|
||||||
|
templateVariaveis: variaveis
|
||||||
|
});
|
||||||
|
statusEl.textContent = resultado.ok
|
||||||
|
? `✅ ${template.name} funcionou${resultado.ticketId ? ` — ticket ${resultado.ticketId}` : ''}`
|
||||||
|
: `❌ ${template.name} falhou: ${resultado.erro}`;
|
||||||
|
statusEl.classList.toggle('status-ok', Boolean(resultado.ok));
|
||||||
|
statusEl.classList.toggle('status-error', !resultado.ok);
|
||||||
|
await carregarOutreach();
|
||||||
|
} catch (error) {
|
||||||
|
statusEl.textContent = `❌ ${template.name} falhou: ${error.message}`;
|
||||||
|
statusEl.classList.add('status-error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
el('btn-toggle-outreach-log').addEventListener('click', () => {
|
||||||
|
const log = el('outreach-ultimos');
|
||||||
|
const hidden = log.classList.toggle('hidden');
|
||||||
|
el('btn-toggle-outreach-log').textContent = hidden ? 'Ver log de envios' : 'Ocultar log de envios';
|
||||||
|
});
|
||||||
|
|
||||||
|
el('btn-enviar-manual').addEventListener('click', async () => {
|
||||||
|
const statusEl = el('manual-status');
|
||||||
|
const oficial = el('manual-canal-oficial').checked;
|
||||||
|
statusEl.classList.remove('status-ok', 'status-error');
|
||||||
|
if (oficial) {
|
||||||
|
const faltando = missingVisibleVariables(Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
if (faltando.length) {
|
||||||
|
statusEl.textContent = `❌ Preencha todas as variáveis do template (${faltando.length} pendente${faltando.length > 1 ? 's' : ''}).`;
|
||||||
|
statusEl.classList.add('status-error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
statusEl.textContent = 'Enviando...';
|
||||||
|
try {
|
||||||
|
const resultado = await API.post('/api/outreach/enviar-manual', {
|
||||||
|
numero: el('manual-numero').value.trim(),
|
||||||
|
canal: oficial ? 'oficial' : 'nao_oficial',
|
||||||
|
mensagem: el('manual-mensagem').value,
|
||||||
|
templateWabaNome: el('manual-template-nome').value.trim(),
|
||||||
|
templateWabaIdioma: el('manual-template-idioma').value.trim(),
|
||||||
|
templateVariaveis: collectVisibleVariablesResolvidas(Array.from(document.querySelectorAll('.manual-template-var'))),
|
||||||
|
templateRota: el('manual-template-rota').value,
|
||||||
|
lead: manualLeadContext
|
||||||
|
});
|
||||||
|
statusEl.textContent = resultado.ok
|
||||||
|
? `✅ Enviado${resultado.ticketId ? ` — ticket ${resultado.ticketId}` : ''}`
|
||||||
|
: `❌ ${resultado.erro}`;
|
||||||
|
statusEl.classList.toggle('status-ok', Boolean(resultado.ok));
|
||||||
|
statusEl.classList.toggle('status-error', !resultado.ok);
|
||||||
|
await carregarOutreach();
|
||||||
|
} catch (error) {
|
||||||
|
statusEl.textContent = `❌ ${error.message}`;
|
||||||
|
statusEl.classList.add('status-error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.GTISelecionarLeadManual = (lead) => {
|
||||||
|
manualLeadContext = lead || null;
|
||||||
|
const template = WABA_TEMPLATE_LIBRARY.find((item) => item.name === el('manual-template-biblioteca').value);
|
||||||
|
atualizarPreview(el('manual-template-preview'), template, Array.from(document.querySelectorAll('.manual-template-var')));
|
||||||
|
};
|
||||||
|
|
||||||
el('btn-salvar-settings').addEventListener('click', async (event) => {
|
el('btn-salvar-settings').addEventListener('click', async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
try {
|
try {
|
||||||
@@ -84,8 +612,18 @@
|
|||||||
'zpro.pipelineId': el('cfg-pipeline').value,
|
'zpro.pipelineId': el('cfg-pipeline').value,
|
||||||
'zpro.stageId': el('cfg-stage').value,
|
'zpro.stageId': el('cfg-stage').value,
|
||||||
'zpro.responsibleId': el('cfg-responsible').value,
|
'zpro.responsibleId': el('cfg-responsible').value,
|
||||||
'zpro.closingForecastDays': el('cfg-forecast').value
|
'zpro.ticketQueueId': el('cfg-ticket-queue').value,
|
||||||
|
'zpro.closingForecastDays': el('cfg-forecast').value,
|
||||||
|
'zpro.baseUrl': el('cfg-zpro-baseurl').value.trim(),
|
||||||
|
'zpro.apiId': el('cfg-zpro-apiid').value.trim(),
|
||||||
|
'zpro.bearerToken': el('cfg-zpro-token').value.trim(),
|
||||||
|
'zpro.whatsappId': el('cfg-zpro-whatsappid').value.trim(),
|
||||||
|
'gchat.templatesUrl': el('cfg-gchat-templates-url').value.trim(),
|
||||||
|
'gchat.bearerToken': el('cfg-gchat-token').value.trim(),
|
||||||
|
'outreach.ativo': el('outreach-ativo').checked ? 'true' : 'false',
|
||||||
|
'outreach.mensagensPorDia': el('outreach-limite').value
|
||||||
});
|
});
|
||||||
|
await carregarOutreach();
|
||||||
el('modal-settings').close();
|
el('modal-settings').close();
|
||||||
toast('Configurações salvas');
|
toast('Configurações salvas');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -96,6 +634,7 @@
|
|||||||
// limpar toda a base (zona de risco)
|
// limpar toda a base (zona de risco)
|
||||||
el('btn-limpar-base').addEventListener('click', () => {
|
el('btn-limpar-base').addEventListener('click', () => {
|
||||||
el('reset-base-senha').value = '';
|
el('reset-base-senha').value = '';
|
||||||
|
el('reset-base-erro').classList.add('hidden');
|
||||||
el('modal-settings').close();
|
el('modal-settings').close();
|
||||||
el('modal-reset-base').showModal();
|
el('modal-reset-base').showModal();
|
||||||
});
|
});
|
||||||
@@ -104,10 +643,17 @@
|
|||||||
el('modal-reset-base').close();
|
el('modal-reset-base').close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Erro aqui precisa aparecer DENTRO do modal (nao so no toast): um <dialog>
|
||||||
|
// aberto via showModal() fica na "top layer" do navegador, acima de
|
||||||
|
// qualquer div normal — inclusive do toast, que ficava invisivel atras do
|
||||||
|
// modal quando a senha estava errada, dando a impressao de que nada
|
||||||
|
// acontecia (bug reportado: "limpeza nao foi feita mesmo pondo a senha").
|
||||||
el('btn-confirmar-reset-base').addEventListener('click', async () => {
|
el('btn-confirmar-reset-base').addEventListener('click', async () => {
|
||||||
|
const erroEl = el('reset-base-erro');
|
||||||
const senha = el('reset-base-senha').value;
|
const senha = el('reset-base-senha').value;
|
||||||
if (!senha) {
|
if (!senha) {
|
||||||
toast('Informe a senha de segurança');
|
erroEl.textContent = 'Informe a senha de segurança';
|
||||||
|
erroEl.classList.remove('hidden');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -116,7 +662,8 @@
|
|||||||
toast('Base de leads limpa com sucesso — recarregando...');
|
toast('Base de leads limpa com sucesso — recarregando...');
|
||||||
setTimeout(() => window.location.reload(), 1200);
|
setTimeout(() => window.location.reload(), 1200);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast(`Erro: ${error.message}`);
|
erroEl.textContent = `Erro: ${error.message}`;
|
||||||
|
erroEl.classList.remove('hidden');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+30
-1
@@ -367,11 +367,40 @@ const Tratamento = (() => {
|
|||||||
|
|
||||||
const tbody = document.querySelector('#tabela-leads tbody');
|
const tbody = document.querySelector('#tabela-leads tbody');
|
||||||
if (!data.rows.length) {
|
if (!data.rows.length) {
|
||||||
tbody.replaceChildren(h('tr', {}, h('td', { colspan: '9', class: 'muted' }, 'Nenhum lead com este filtro.')));
|
tbody.replaceChildren(h('tr', {}, h('td', { colspan: '10', class: 'muted' }, 'Nenhum lead com este filtro.')));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const abrirWhatsAppLead = async (event, lead) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
if (!lead.whatsapp) {
|
||||||
|
toast('Este lead não tem WhatsApp cadastrado');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let leadCompleto = lead;
|
||||||
|
try {
|
||||||
|
leadCompleto = await API.get(`/api/leads/${lead.id}`);
|
||||||
|
} catch {
|
||||||
|
leadCompleto = lead;
|
||||||
|
}
|
||||||
|
const settingsButton = el('btn-settings');
|
||||||
|
settingsButton.click();
|
||||||
|
setTimeout(() => {
|
||||||
|
window.GTISelecionarLeadManual?.(leadCompleto);
|
||||||
|
el('manual-numero').value = leadCompleto.whatsapp || lead.whatsapp;
|
||||||
|
el('manual-canal-naooficial').checked = true;
|
||||||
|
el('manual-canal-naooficial').dispatchEvent(new Event('change'));
|
||||||
|
el('manual-mensagem').value = `Olá ${leadCompleto.empresa || lead.empresa}! Somos do Grupo GTI. Podemos conversar?`;
|
||||||
|
el('manual-status').textContent = '';
|
||||||
|
}, 250);
|
||||||
|
};
|
||||||
|
|
||||||
tbody.replaceChildren(...data.rows.map((lead) => h('tr', { onclick: () => abrirLead(lead.id) },
|
tbody.replaceChildren(...data.rows.map((lead) => h('tr', { onclick: () => abrirLead(lead.id) },
|
||||||
|
h('td', { class: 'acao-col' }, h('button', {
|
||||||
|
class: 'whatsapp-action',
|
||||||
|
title: 'Enviar WhatsApp para este lead',
|
||||||
|
onclick: (event) => abrirWhatsAppLead(event, lead)
|
||||||
|
}, '☎')),
|
||||||
h('td', { class: 'empresa-cell', title: lead.legal_name || lead.empresa }, lead.empresa),
|
h('td', { class: 'empresa-cell', title: lead.legal_name || lead.empresa }, lead.empresa),
|
||||||
h('td', {}, lead.whatsapp || '—'),
|
h('td', {}, lead.whatsapp || '—'),
|
||||||
h('td', {}, lead.cidade),
|
h('td', {}, lead.cidade),
|
||||||
|
|||||||
+6
-4
@@ -5,21 +5,23 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>GTI Máquina Comercial — Login</title>
|
<title>GTI Máquina Comercial — Login</title>
|
||||||
<link rel="stylesheet" href="/css/app.css">
|
<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>">
|
<link rel="icon" href="/img/logo-gti.png">
|
||||||
</head>
|
</head>
|
||||||
<body class="login-body">
|
<body class="login-body">
|
||||||
|
|
||||||
<main class="login-wrap">
|
<main class="login-wrap">
|
||||||
<form class="card login-card" id="form-login">
|
<form class="card login-card" id="form-login">
|
||||||
<div class="brand login-brand">
|
<div class="brand login-brand">
|
||||||
<span class="brand-mark">GTI</span>
|
<img class="brand-mark brand-mark-lg" src="/img/logo-gti.png" alt="GTI">
|
||||||
<span class="brand-name">Máquina Comercial</span>
|
<span class="brand-name">Máquina Comercial</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Usuário <input type="text" id="login-username" autocomplete="username" required></label>
|
<label for="login-username">Usuário</label>
|
||||||
|
<input type="text" id="login-username" autocomplete="username" required>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Senha <input type="password" id="login-password" autocomplete="current-password" required></label>
|
<label for="login-password">Senha</label>
|
||||||
|
<input type="password" id="login-password" autocomplete="current-password" required>
|
||||||
</div>
|
</div>
|
||||||
<p class="muted login-erro" id="login-erro"></p>
|
<p class="muted login-erro" id="login-erro"></p>
|
||||||
<button class="btn btn-primary btn-lg" type="submit">Entrar</button>
|
<button class="btn btn-primary btn-lg" type="submit">Entrar</button>
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { loadDotEnv } from '../src/env.mjs';
|
||||||
|
import { openDb, ensureSeeds } from '../src/db.mjs';
|
||||||
|
import { runOutreachBatch } from '../src/outreach/run.mjs';
|
||||||
|
|
||||||
|
// Dispara um lote manual da automacao de envio WhatsApp (Z-PRO), fora do
|
||||||
|
// ciclo automatico de 20 min do servidor. Util pra testar ou forcar um lote
|
||||||
|
// extra sem reiniciar o servidor:
|
||||||
|
// node scripts/enviar-outreach.mjs (ou npm run outreach)
|
||||||
|
//
|
||||||
|
// Respeita as mesmas regras do ciclo automatico (outreach.ativo, horario
|
||||||
|
// comercial, limite diario) — nao manda nada "escondido" do que a tela
|
||||||
|
// de Configuracoes mostra.
|
||||||
|
|
||||||
|
await loadDotEnv();
|
||||||
|
|
||||||
|
const log = (message) => console.log(`[outreach] ${message}`);
|
||||||
|
|
||||||
|
const db = openDb();
|
||||||
|
await ensureSeeds(db, { log });
|
||||||
|
|
||||||
|
const resumo = await runOutreachBatch({ db, log });
|
||||||
|
console.log(JSON.stringify(resumo, null, 2));
|
||||||
|
|
||||||
|
db.close();
|
||||||
@@ -2,6 +2,7 @@ import { loadDotEnv, GTI_PORT } from '../src/env.mjs';
|
|||||||
import { openDb, ensureSeeds } from '../src/db.mjs';
|
import { openDb, ensureSeeds } from '../src/db.mjs';
|
||||||
import { createJobManager, recoverOrphans } from '../src/jobs/manager.mjs';
|
import { createJobManager, recoverOrphans } from '../src/jobs/manager.mjs';
|
||||||
import { createAppServer } from '../src/server/index.mjs';
|
import { createAppServer } from '../src/server/index.mjs';
|
||||||
|
import { startOutreachScheduler } from '../src/outreach/scheduler.mjs';
|
||||||
|
|
||||||
// Servidor local do GTI Maquina Comercial. Inicie com:
|
// Servidor local do GTI Maquina Comercial. Inicie com:
|
||||||
// npm start (ou node scripts/servidor.mjs, ou o GTI-Comercial.exe)
|
// npm start (ou node scripts/servidor.mjs, ou o GTI-Comercial.exe)
|
||||||
@@ -17,6 +18,7 @@ recoverOrphans(db, log);
|
|||||||
|
|
||||||
const jobs = createJobManager();
|
const jobs = createJobManager();
|
||||||
const server = createAppServer({ db, jobs, log });
|
const server = createAppServer({ db, jobs, log });
|
||||||
|
startOutreachScheduler({ db, log });
|
||||||
|
|
||||||
const port = GTI_PORT;
|
const port = GTI_PORT;
|
||||||
server.listen(port, '127.0.0.1', () => {
|
server.listen(port, '127.0.0.1', () => {
|
||||||
|
|||||||
@@ -34,9 +34,9 @@ export async function runCapture({ db, runId, params, emit = () => {}, log = ()
|
|||||||
endpoints,
|
endpoints,
|
||||||
delays: {
|
delays: {
|
||||||
overpassDelayMs: envNumber('OVERPASS_REQUEST_DELAY_MS', 5000),
|
overpassDelayMs: envNumber('OVERPASS_REQUEST_DELAY_MS', 5000),
|
||||||
overpassTimeoutMs: envNumber('OVERPASS_TIMEOUT_MS', 30000)
|
overpassTimeoutMs: envNumber('OVERPASS_TIMEOUT_MS', 15000)
|
||||||
},
|
},
|
||||||
overpassTextSearch: envString('OVERPASS_TEXT_SEARCH', 'true') !== 'false',
|
overpassTextSearch: envString('OVERPASS_TEXT_SEARCH', 'false') === 'true',
|
||||||
geocode: createGeocoder(db, { nominatimUrl: endpoints.nominatimUrl })
|
geocode: createGeocoder(db, { nominatimUrl: endpoints.nominatimUrl })
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+139
-2
@@ -167,6 +167,77 @@ const MIGRATIONS = [
|
|||||||
role TEXT NOT NULL DEFAULT 'comercial',
|
role TEXT NOT NULL DEFAULT 'comercial',
|
||||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
);
|
);
|
||||||
|
`,
|
||||||
|
// v4 — automacao de envio WhatsApp (Z-PRO): um template de mensagem por
|
||||||
|
// produto/servico, e o historico de disparos (o que foi mandado, pra quem,
|
||||||
|
// quando) usado tanto pra nao repetir envio quanto pra decidir quando tentar
|
||||||
|
// o proximo produto recomendado.
|
||||||
|
`
|
||||||
|
CREATE TABLE message_templates (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
produto TEXT NOT NULL UNIQUE,
|
||||||
|
mensagem TEXT NOT NULL,
|
||||||
|
ativo INTEGER NOT NULL DEFAULT 1,
|
||||||
|
updated_at TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE outreach_sends (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
lead_id INTEGER NOT NULL REFERENCES leads(id),
|
||||||
|
produto TEXT NOT NULL,
|
||||||
|
mensagem_enviada TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'enviado',
|
||||||
|
erro TEXT,
|
||||||
|
zpro_ticket_id TEXT,
|
||||||
|
sent_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_outreach_lead_produto ON outreach_sends(lead_id, produto);
|
||||||
|
CREATE INDEX idx_outreach_sent_at ON outreach_sends(sent_at);
|
||||||
|
`,
|
||||||
|
// v5 — canal de envio por template: 'nao_oficial' (texto livre, bulkIndividual,
|
||||||
|
// conexao QR/Baileys) ou 'oficial' (API oficial Meta/WABA, exige template
|
||||||
|
// ja aprovado no Meta Business Manager — nao da pra criar/aprovar por aqui).
|
||||||
|
`
|
||||||
|
ALTER TABLE message_templates ADD COLUMN canal TEXT NOT NULL DEFAULT 'nao_oficial';
|
||||||
|
ALTER TABLE message_templates ADD COLUMN template_waba_nome TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE message_templates ADD COLUMN template_waba_idioma TEXT NOT NULL DEFAULT 'pt_BR';
|
||||||
|
|
||||||
|
ALTER TABLE outreach_sends ADD COLUMN canal TEXT NOT NULL DEFAULT 'nao_oficial';
|
||||||
|
`,
|
||||||
|
// v6 — envio manual avulso (mandar mensagem pra um numero especifico, sem
|
||||||
|
// estar ligado a um lead da base). lead_id precisa virar opcional (SQLite
|
||||||
|
// nao remove NOT NULL com ALTER TABLE direto, por isso o rebuild da tabela)
|
||||||
|
// e numero/origem guardam pra quem foi e se foi automatico ou manual.
|
||||||
|
`
|
||||||
|
CREATE TABLE outreach_sends_v6 (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
lead_id INTEGER REFERENCES leads(id),
|
||||||
|
produto TEXT NOT NULL DEFAULT '',
|
||||||
|
numero TEXT,
|
||||||
|
mensagem_enviada TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'enviado',
|
||||||
|
erro TEXT,
|
||||||
|
zpro_ticket_id TEXT,
|
||||||
|
canal TEXT NOT NULL DEFAULT 'nao_oficial',
|
||||||
|
origem TEXT NOT NULL DEFAULT 'automatico',
|
||||||
|
sent_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO outreach_sends_v6
|
||||||
|
(id, lead_id, produto, mensagem_enviada, status, erro, zpro_ticket_id, canal, sent_at)
|
||||||
|
SELECT id, lead_id, produto, mensagem_enviada, status, erro, zpro_ticket_id, canal, sent_at
|
||||||
|
FROM outreach_sends;
|
||||||
|
|
||||||
|
DROP TABLE outreach_sends;
|
||||||
|
ALTER TABLE outreach_sends_v6 RENAME TO outreach_sends;
|
||||||
|
|
||||||
|
CREATE INDEX idx_outreach_lead_produto ON outreach_sends(lead_id, produto);
|
||||||
|
CREATE INDEX idx_outreach_sent_at ON outreach_sends(sent_at);
|
||||||
|
`,
|
||||||
|
// v7 — variaveis dos templates WABA automaticos por produto. Cada item pode
|
||||||
|
// usar placeholders resolvidos por lead: {empresa}, {produto}, {cidade}, etc.
|
||||||
|
`
|
||||||
|
ALTER TABLE message_templates ADD COLUMN template_waba_variaveis_json TEXT NOT NULL DEFAULT '[]';
|
||||||
`
|
`
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -268,10 +339,31 @@ const DEFAULT_SETTINGS = {
|
|||||||
'zpro.pipelineId': '1',
|
'zpro.pipelineId': '1',
|
||||||
'zpro.stageId': '1',
|
'zpro.stageId': '1',
|
||||||
'zpro.responsibleId': '15',
|
'zpro.responsibleId': '15',
|
||||||
|
'zpro.ticketQueueId': '12',
|
||||||
'zpro.status': 'open',
|
'zpro.status': 'open',
|
||||||
'zpro.closingForecastDays': '30',
|
'zpro.closingForecastDays': '30',
|
||||||
'zpro.validateNumber': 'true',
|
'zpro.validateNumber': 'true',
|
||||||
'meta_diaria': '100'
|
// Credenciais da API externa do Z-PRO usadas pela automacao de envio
|
||||||
|
// WhatsApp (src/outreach/zpro-client.mjs). Editaveis em Configuracoes >
|
||||||
|
// Credenciais Z-PRO; vazio aqui cai pro .env (ZPRO_BASE_URL/etc) se existir.
|
||||||
|
'zpro.baseUrl': '',
|
||||||
|
'zpro.apiId': '',
|
||||||
|
'zpro.bearerToken': '',
|
||||||
|
'zpro.whatsappId': '',
|
||||||
|
'meta_diaria': '100',
|
||||||
|
// Automacao de envio WhatsApp (Z-PRO) — comeca desligada de proposito:
|
||||||
|
// so liga depois que o .env tiver as credenciais e os templates forem revisados.
|
||||||
|
'outreach.ativo': 'false',
|
||||||
|
'outreach.mensagensPorDia': '10',
|
||||||
|
'outreach.diasEntreProdutos': '5',
|
||||||
|
'outreach.tentarProximoProduto': 'false',
|
||||||
|
'outreach.horaInicio': '08:00',
|
||||||
|
'outreach.horaFim': '18:00',
|
||||||
|
// Endpoint interno do GChat que lista templates WABA do canal GRUPO GTI COEX.
|
||||||
|
// O token de sessao do GChat deve ser preenchido localmente na tela; nao fica
|
||||||
|
// embutido no codigo.
|
||||||
|
'gchat.templatesUrl': 'https://apigchat.gtigrupo.com.br/wabametaTemplate/1126322523899986',
|
||||||
|
'gchat.bearerToken': ''
|
||||||
};
|
};
|
||||||
|
|
||||||
export function seedSettings(db, extra = {}) {
|
export function seedSettings(db, extra = {}) {
|
||||||
@@ -388,6 +480,47 @@ function countRows(db, table) {
|
|||||||
return db.prepare(`SELECT COUNT(*) AS total FROM ${table}`).get().total;
|
return db.prepare(`SELECT COUNT(*) AS total FROM ${table}`).get().total;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MENSAGEM_PADRAO =
|
||||||
|
'Ola! Somos o Grupo GTI. Notamos que a {empresa} pode se beneficiar do nosso ' +
|
||||||
|
'{produto} — ajudamos empresas em {cidade} com isso. Podemos conversar?';
|
||||||
|
|
||||||
|
// Um template por produto/servico (INSERT OR IGNORE: nao sobrescreve texto ja
|
||||||
|
// editado pelo usuario na tela de Configuracoes ao reaplicar em boots seguintes).
|
||||||
|
export function seedMessageTemplates(db, produtos) {
|
||||||
|
transaction(db, () => {
|
||||||
|
const stmt = db.prepare('INSERT OR IGNORE INTO message_templates (produto, mensagem) VALUES (?, ?)');
|
||||||
|
for (const produto of produtos) {
|
||||||
|
if (!produto) continue;
|
||||||
|
stmt.run(produto, MENSAGEM_PADRAO.replace('{produto}', produto));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listMessageTemplates(db) {
|
||||||
|
return db.prepare('SELECT * FROM message_templates ORDER BY produto').all();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMessageTemplate(db, produto, { mensagem, ativo, canal, templateWabaNome, templateWabaIdioma, templateWabaVariaveis }) {
|
||||||
|
const row = db.prepare('SELECT * FROM message_templates WHERE produto = ?').get(produto);
|
||||||
|
if (!row) return null;
|
||||||
|
const novaMensagem = mensagem !== undefined ? mensagem : row.mensagem;
|
||||||
|
const novoAtivo = ativo !== undefined ? (ativo ? 1 : 0) : row.ativo;
|
||||||
|
const novoCanal = canal === 'oficial' ? 'oficial' : canal === 'nao_oficial' ? 'nao_oficial' : row.canal;
|
||||||
|
const novoNome = templateWabaNome !== undefined ? templateWabaNome : row.template_waba_nome;
|
||||||
|
const novoIdioma = templateWabaIdioma !== undefined ? templateWabaIdioma : row.template_waba_idioma;
|
||||||
|
const novasVariaveis = templateWabaVariaveis !== undefined
|
||||||
|
? JSON.stringify((Array.isArray(templateWabaVariaveis) ? templateWabaVariaveis : [])
|
||||||
|
.map((value) => String(value || '').trim())
|
||||||
|
.filter(Boolean))
|
||||||
|
: row.template_waba_variaveis_json;
|
||||||
|
db.prepare(
|
||||||
|
`UPDATE message_templates
|
||||||
|
SET mensagem = ?, ativo = ?, canal = ?, template_waba_nome = ?, template_waba_idioma = ?, template_waba_variaveis_json = ?, updated_at = datetime('now')
|
||||||
|
WHERE produto = ?`
|
||||||
|
).run(novaMensagem, novoAtivo, novoCanal, novoNome, novoIdioma, novasVariaveis, produto);
|
||||||
|
return db.prepare('SELECT * FROM message_templates WHERE produto = ?').get(produto);
|
||||||
|
}
|
||||||
|
|
||||||
// Popula tabelas de referencia na primeira execucao. Tolerante a arquivos de
|
// Popula tabelas de referencia na primeira execucao. Tolerante a arquivos de
|
||||||
// seed ausentes (loga e segue) para o servidor nunca falhar no boot por isso.
|
// seed ausentes (loga e segue) para o servidor nunca falhar no boot por isso.
|
||||||
export async function ensureSeeds(db, { log = () => {} } = {}) {
|
export async function ensureSeeds(db, { log = () => {} } = {}) {
|
||||||
@@ -399,7 +532,11 @@ export async function ensureSeeds(db, { log = () => {} } = {}) {
|
|||||||
const config = JSON.parse(await fsp.readFile(paths.config, 'utf8'));
|
const config = JSON.parse(await fsp.readFile(paths.config, 'utf8'));
|
||||||
seedSegments(db, config.segments || []);
|
seedSegments(db, config.segments || []);
|
||||||
if (countRows(db, 'geo_cache') === 0) seedGeoCache(db, config.cityAreas || []);
|
if (countRows(db, 'geo_cache') === 0) seedGeoCache(db, config.cityAreas || []);
|
||||||
log(`seeds: ${countRows(db, 'segments')} segmentos, ${countRows(db, 'geo_cache')} bboxes`);
|
const produtos = [...new Set(
|
||||||
|
(config.segments || []).flatMap((s) => (s.products || []).map((p) => p.nome)).filter(Boolean)
|
||||||
|
)];
|
||||||
|
seedMessageTemplates(db, produtos);
|
||||||
|
log(`seeds: ${countRows(db, 'segments')} segmentos, ${countRows(db, 'geo_cache')} bboxes, ${countRows(db, 'message_templates')} templates`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
log(`seeds: config.json indisponivel (${error.message})`);
|
log(`seeds: config.json indisponivel (${error.message})`);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-2
@@ -18,6 +18,15 @@ export const paths = {
|
|||||||
public: path.join(projectRoot, 'public')
|
public: path.join(projectRoot, 'public')
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export let GTI_PORT = envNumber('GTI_PORT', 3900);
|
||||||
|
|
||||||
|
function refreshEnvDerivedValues() {
|
||||||
|
paths.db = process.env.GTI_DB_PATH || path.join(projectRoot, 'data', 'gti.db');
|
||||||
|
paths.cnpjDir = process.env.CNPJ_BASE_DIR || path.join(projectRoot, 'prospeccao', 'cnpj');
|
||||||
|
paths.rfbRaw = path.join(paths.cnpjDir, 'rfb-raw');
|
||||||
|
GTI_PORT = envNumber('GTI_PORT', 3900);
|
||||||
|
}
|
||||||
|
|
||||||
export async function loadDotEnv(rootDir = projectRoot) {
|
export async function loadDotEnv(rootDir = projectRoot) {
|
||||||
try {
|
try {
|
||||||
const content = await fs.readFile(path.join(rootDir, '.env'), 'utf8');
|
const content = await fs.readFile(path.join(rootDir, '.env'), 'utf8');
|
||||||
@@ -33,6 +42,8 @@ export async function loadDotEnv(rootDir = projectRoot) {
|
|||||||
const value = trimmed.slice(separator + 1).trim();
|
const value = trimmed.slice(separator + 1).trim();
|
||||||
if (!process.env[key]) process.env[key] = value;
|
if (!process.env[key]) process.env[key] = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
refreshEnvDerivedValues();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code !== 'ENOENT') throw error;
|
if (error.code !== 'ENOENT') throw error;
|
||||||
}
|
}
|
||||||
@@ -46,5 +57,3 @@ export function envNumber(name, fallback) {
|
|||||||
export function envString(name, fallback) {
|
export function envString(name, fallback) {
|
||||||
return process.env[name] || fallback;
|
return process.env[name] || fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GTI_PORT = envNumber('GTI_PORT', 3900);
|
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { getSetting, listMessageTemplates } from '../db.mjs';
|
||||||
|
import { renderTemplate } from './templates.mjs';
|
||||||
|
import { createZproClient } from './zpro-client.mjs';
|
||||||
|
|
||||||
|
// Intervalo aleatorio entre envios (mesmo padrao dos endpoints de bulk do
|
||||||
|
// proprio Z-PRO) para nao parecer disparo automatizado agressivo.
|
||||||
|
const INTERVALO_MIN_MS = 3000;
|
||||||
|
const INTERVALO_MAX_MS = 8000;
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
function withinBusinessHours(horaInicio, horaFim, now = new Date()) {
|
||||||
|
const hhmm = now.toTimeString().slice(0, 5);
|
||||||
|
return hhmm >= horaInicio && hhmm <= horaFim;
|
||||||
|
}
|
||||||
|
|
||||||
|
function lastEnviado(db, leadId, produto) {
|
||||||
|
return db.prepare(
|
||||||
|
"SELECT * FROM outreach_sends WHERE lead_id = ? AND produto = ? AND status = 'enviado' ORDER BY sent_at DESC LIMIT 1"
|
||||||
|
).get(leadId, produto);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decide qual produto tentar pra um lead, olhando o historico de envios:
|
||||||
|
// - cascata desligada (padrao): so tenta o produto principal, uma vez.
|
||||||
|
// - cascata ligada: percorre os produtos em ordem de estrelas; usa o primeiro
|
||||||
|
// nunca enviado, ou pula pro proximo se o ultimo envio ja passou do prazo
|
||||||
|
// de espera. Se o produto atual ainda esta "no prazo", o lead e pulado
|
||||||
|
// nessa rodada (nao aumenta o consumo do limite diario).
|
||||||
|
function pickProduto(db, lead, { tentarProximoProduto, diasEntreProdutos }) {
|
||||||
|
const produtos = JSON.parse(lead.produtos_json || '[]')
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => (b.estrelas || 0) - (a.estrelas || 0))
|
||||||
|
.map((p) => p.nome)
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!produtos.length) return null;
|
||||||
|
|
||||||
|
if (tentarProximoProduto !== 'true') {
|
||||||
|
const produto = produtos[0];
|
||||||
|
return lastEnviado(db, lead.id, produto) ? null : produto;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const produto of produtos) {
|
||||||
|
const ultimo = lastEnviado(db, lead.id, produto);
|
||||||
|
if (!ultimo) return produto;
|
||||||
|
const diasPassados = (Date.now() - new Date(`${ultimo.sent_at}Z`).getTime()) / 86400000;
|
||||||
|
if (diasPassados < Number(diasEntreProdutos)) return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function priorityTagName(prioridade) {
|
||||||
|
return `GTI P${prioridade || 4}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function offerTagName(produto) {
|
||||||
|
return `GTI Oferta: ${produto}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateVariablesForLead(template, lead, produto) {
|
||||||
|
let configured = [];
|
||||||
|
try {
|
||||||
|
configured = JSON.parse(template.template_waba_variaveis_json || '[]');
|
||||||
|
} catch {
|
||||||
|
configured = [];
|
||||||
|
}
|
||||||
|
const variables = Array.isArray(configured) && configured.length
|
||||||
|
? configured
|
||||||
|
: ['{empresa}', '{produto}'];
|
||||||
|
const data = { ...lead, produto };
|
||||||
|
return variables
|
||||||
|
.map((value) => renderTemplate(String(value || ''), data).trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache em memoria (por lote) de nome de tag -> id: evita chamar listTags a
|
||||||
|
// cada lead e evita criar a mesma tag duas vezes.
|
||||||
|
async function ensureTagIds(zproClient, nomes, cache) {
|
||||||
|
if (!cache.loaded) {
|
||||||
|
const resposta = await zproClient.listTags({ isActive: true });
|
||||||
|
const lista = Array.isArray(resposta) ? resposta : resposta?.data || resposta?.tags || [];
|
||||||
|
for (const tag of lista) {
|
||||||
|
if (tag?.tag) cache.map.set(tag.tag, tag.id);
|
||||||
|
}
|
||||||
|
cache.loaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ids = [];
|
||||||
|
for (const nome of nomes) {
|
||||||
|
let id = cache.map.get(nome);
|
||||||
|
if (!id) {
|
||||||
|
const criada = await zproClient.createTag({ tag: nome });
|
||||||
|
id = criada?.id || criada?.data?.id;
|
||||||
|
if (id) cache.map.set(nome, id);
|
||||||
|
}
|
||||||
|
if (id) ids.push(id);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Um lote de disparo automatico: verifica se esta ligado/dentro do horario/
|
||||||
|
// dentro do limite diario, escolhe candidatos elegiveis e manda uma mensagem
|
||||||
|
// por lead via bulkIndividual, registrando tudo em outreach_sends e aplicando
|
||||||
|
// tags de prioridade + oferta no contato do Z-PRO.
|
||||||
|
export async function runOutreachBatch({ db, zproClient = createZproClient(db), log = () => {} }) {
|
||||||
|
const resumo = { tentados: 0, enviados: 0, erros: 0, pulados: 0 };
|
||||||
|
|
||||||
|
if (getSetting(db, 'outreach.ativo', 'false') !== 'true') {
|
||||||
|
log('outreach: desativado (outreach.ativo=false)');
|
||||||
|
return resumo;
|
||||||
|
}
|
||||||
|
|
||||||
|
const horaInicio = getSetting(db, 'outreach.horaInicio', '08:00');
|
||||||
|
const horaFim = getSetting(db, 'outreach.horaFim', '18:00');
|
||||||
|
if (!withinBusinessHours(horaInicio, horaFim)) {
|
||||||
|
log(`outreach: fora do horario comercial (${horaInicio}-${horaFim})`);
|
||||||
|
return resumo;
|
||||||
|
}
|
||||||
|
|
||||||
|
const limiteDiario = Number(getSetting(db, 'outreach.mensagensPorDia', '10')) || 0;
|
||||||
|
const jaEnviadosHoje = db.prepare(
|
||||||
|
"SELECT COUNT(*) AS t FROM outreach_sends WHERE status = 'enviado' AND date(sent_at) = date('now')"
|
||||||
|
).get().t;
|
||||||
|
let restante = limiteDiario - jaEnviadosHoje;
|
||||||
|
if (restante <= 0) {
|
||||||
|
log(`outreach: limite diario atingido (${jaEnviadosHoje}/${limiteDiario})`);
|
||||||
|
return resumo;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tentarProximoProduto = getSetting(db, 'outreach.tentarProximoProduto', 'false');
|
||||||
|
const diasEntreProdutos = getSetting(db, 'outreach.diasEntreProdutos', '5');
|
||||||
|
const templates = new Map(listMessageTemplates(db).map((t) => [t.produto, t]));
|
||||||
|
|
||||||
|
const candidatos = db.prepare(
|
||||||
|
`SELECT id, empresa, cidade, segmento, segmento_label, whatsapp, prioridade, produtos_json
|
||||||
|
FROM leads
|
||||||
|
WHERE exported_at IS NULL AND telefone_valido = 1 AND whatsapp != '' AND produto_principal != ''
|
||||||
|
ORDER BY prioridade ASC, score DESC`
|
||||||
|
).all();
|
||||||
|
|
||||||
|
const insertSend = db.prepare(
|
||||||
|
`INSERT INTO outreach_sends (lead_id, produto, mensagem_enviada, status, erro, zpro_ticket_id, canal)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
);
|
||||||
|
const tagCache = { loaded: false, map: new Map() };
|
||||||
|
|
||||||
|
for (let i = 0; i < candidatos.length; i += 1) {
|
||||||
|
const lead = candidatos[i];
|
||||||
|
if (restante <= 0) break;
|
||||||
|
|
||||||
|
const produto = pickProduto(db, lead, { tentarProximoProduto, diasEntreProdutos });
|
||||||
|
if (!produto) {
|
||||||
|
resumo.pulados += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const template = templates.get(produto);
|
||||||
|
if (!template || !template.ativo) {
|
||||||
|
resumo.pulados += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const canal = template.canal === 'oficial' ? 'oficial' : 'nao_oficial';
|
||||||
|
if (canal === 'oficial' && !template.template_waba_nome) {
|
||||||
|
log(`outreach: produto "${produto}" no canal oficial sem template aprovado configurado — lead #${lead.id} pulado`);
|
||||||
|
resumo.pulados += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
resumo.tentados += 1;
|
||||||
|
const externalKey = `gti-lead-${lead.id}-${produto}-${Date.now()}`;
|
||||||
|
const mensagem = canal === 'oficial'
|
||||||
|
? `template:${template.template_waba_nome}/${template.template_waba_idioma}`
|
||||||
|
: renderTemplate(template.mensagem, lead);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const resposta = canal === 'oficial'
|
||||||
|
? await zproClient.sendTemplateWaba({
|
||||||
|
number: lead.whatsapp,
|
||||||
|
templateName: template.template_waba_nome,
|
||||||
|
languageCode: template.template_waba_idioma,
|
||||||
|
variables: templateVariablesForLead(template, lead, produto)
|
||||||
|
})
|
||||||
|
: await zproClient.sendText({ number: lead.whatsapp, message: mensagem, externalKey });
|
||||||
|
const ticketId = resposta?.ticketId || resposta?.data?.ticketId ? String(resposta.ticketId || resposta.data.ticketId) : null;
|
||||||
|
insertSend.run(lead.id, produto, mensagem, 'enviado', null, ticketId, canal);
|
||||||
|
resumo.enviados += 1;
|
||||||
|
restante -= 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tagIds = await ensureTagIds(
|
||||||
|
zproClient,
|
||||||
|
[priorityTagName(lead.prioridade), offerTagName(produto)],
|
||||||
|
tagCache
|
||||||
|
);
|
||||||
|
if (tagIds.length) await zproClient.addTagContact({ number: lead.whatsapp, tagIds });
|
||||||
|
} catch (tagError) {
|
||||||
|
log(`outreach: falha ao aplicar tags do lead #${lead.id}: ${tagError.message}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
insertSend.run(lead.id, produto, mensagem, 'erro', String(error.message || error), null, canal);
|
||||||
|
resumo.erros += 1;
|
||||||
|
log(`outreach: erro ao enviar lead #${lead.id} (${produto}): ${error.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (restante > 0 && i < candidatos.length - 1) {
|
||||||
|
await sleep(INTERVALO_MIN_MS + Math.random() * (INTERVALO_MAX_MS - INTERVALO_MIN_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log(`outreach: ${resumo.enviados} enviados, ${resumo.erros} erros, ${resumo.pulados} pulados (tentados ${resumo.tentados})`);
|
||||||
|
return resumo;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { runOutreachBatch } from './run.mjs';
|
||||||
|
|
||||||
|
const CICLO_MS = 20 * 60 * 1000;
|
||||||
|
|
||||||
|
// Timer interno no processo do servidor: nao depende de agendador do sistema
|
||||||
|
// operacional (Task Scheduler/cron), entao funciona identico local (Windows)
|
||||||
|
// ou dentro de um container Docker apos a migracao — so precisa do servidor
|
||||||
|
// estar de pe, o que ja e verdade hoje. runOutreachBatch e idempotente e sai
|
||||||
|
// cedo quando desligado/fora de horario/limite batido, entao rodar a cada
|
||||||
|
// 20 min e seguro sem lock ou fila.
|
||||||
|
export function startOutreachScheduler({ db, log = () => {} }) {
|
||||||
|
const ciclo = () => {
|
||||||
|
runOutreachBatch({ db, log }).catch((error) => {
|
||||||
|
log(`outreach: erro inesperado no ciclo automatico: ${error.message}`);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// roda um primeiro ciclo pouco depois do boot (idempotente/seguro), sem
|
||||||
|
// esperar os 20 min inteiros para o primeiro lote do dia.
|
||||||
|
const primeiro = setTimeout(ciclo, 30 * 1000);
|
||||||
|
primeiro.unref();
|
||||||
|
|
||||||
|
const timer = setInterval(ciclo, CICLO_MS);
|
||||||
|
timer.unref();
|
||||||
|
return () => {
|
||||||
|
clearTimeout(primeiro);
|
||||||
|
clearInterval(timer);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
export const COMMERCIAL_VARIABLES = [
|
||||||
|
{ key: 'name', label: 'Nome do WhatsApp/contato' },
|
||||||
|
{ key: 'empresa', label: 'Nome da empresa' },
|
||||||
|
{ key: 'businessName', label: 'Nome da empresa (GChat)' },
|
||||||
|
{ key: 'firstName', label: 'Primeiro nome' },
|
||||||
|
{ key: 'produto', label: 'Produto recomendado' },
|
||||||
|
{ key: 'protocol', label: 'Assunto/protocolo' },
|
||||||
|
{ key: 'cidade', label: 'Cidade' },
|
||||||
|
{ key: 'uf', label: 'UF' },
|
||||||
|
{ key: 'segmento', label: 'Nicho/segmento' },
|
||||||
|
{ key: 'cnpj', label: 'CNPJ' },
|
||||||
|
{ key: 'email', label: 'E-mail' },
|
||||||
|
{ key: 'phoneNumber', label: 'WhatsApp/telefone' },
|
||||||
|
{ key: 'whatsapp', label: 'WhatsApp/telefone' },
|
||||||
|
{ key: 'kanban', label: 'Produto/interesse' },
|
||||||
|
{ key: 'user', label: 'Usuário/remetente' },
|
||||||
|
{ key: 'userEmail', label: 'E-mail do remetente' },
|
||||||
|
{ key: 'greeting', label: 'Saudação' }
|
||||||
|
];
|
||||||
|
|
||||||
|
export function commercialVariableValues(lead = {}) {
|
||||||
|
const empresa = lead.empresa || lead.businessName || lead.name || 'sua empresa';
|
||||||
|
const produto = lead.produto || lead.produto_principal || lead.interesse || 'Atendimento comercial';
|
||||||
|
const cidade = lead.cidade || 'sua regiao';
|
||||||
|
const segmento = lead.segmento_label || lead.segmento || '';
|
||||||
|
const phoneNumber = lead.whatsapp || lead.phoneNumber || '';
|
||||||
|
const firstName = String(lead.name || empresa).split(/\s+/).filter(Boolean)[0] || empresa;
|
||||||
|
return {
|
||||||
|
name: lead.name || empresa,
|
||||||
|
empresa,
|
||||||
|
businessName: empresa,
|
||||||
|
firstName,
|
||||||
|
lastName: lead.lastName || '',
|
||||||
|
produto,
|
||||||
|
protocol: lead.protocol || produto,
|
||||||
|
cidade,
|
||||||
|
uf: lead.uf || '',
|
||||||
|
segmento,
|
||||||
|
cnpj: lead.cnpj || '',
|
||||||
|
email: lead.email || '',
|
||||||
|
phoneNumber,
|
||||||
|
whatsapp: phoneNumber,
|
||||||
|
kanban: lead.kanban || produto,
|
||||||
|
user: lead.user || 'Grupo GTI',
|
||||||
|
userEmail: lead.userEmail || 'comercial@gtigrupo.com.br',
|
||||||
|
greeting: 'Ola'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Substituicao simples de variaveis no texto do template. Cada mensagem ja e
|
||||||
|
// resolvida por completo antes de chamar o Z-PRO (bulkIndividual manda texto
|
||||||
|
// pronto), entao nao dependemos da substituicao posicional por CSV que o
|
||||||
|
// bulkSendMessageWithVariable do Z-PRO usa.
|
||||||
|
export function renderTemplate(mensagem, lead) {
|
||||||
|
const values = commercialVariableValues(lead);
|
||||||
|
let output = String(mensagem || '')
|
||||||
|
.replaceAll('{empresa}', values.empresa)
|
||||||
|
.replaceAll('{cidade}', values.cidade)
|
||||||
|
.replaceAll('{produto}', values.produto)
|
||||||
|
.replaceAll('{segmento}', values.segmento);
|
||||||
|
for (const [key, value] of Object.entries(values)) {
|
||||||
|
output = output.replaceAll(`{{${key}}}`, value);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { getSetting, setSetting } from '../db.mjs';
|
||||||
|
|
||||||
|
export const DEFAULT_WABA_TEMPLATES = [
|
||||||
|
{ name: 'gti_inicio_atendimento_solicitado', label: 'Inicio de atendimento solicitado', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}', 'Atendimento sobre {produto}'] },
|
||||||
|
{ name: 'gti_agendamento_suporte_remoto', label: 'Agendamento de suporte remoto', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}'] },
|
||||||
|
{ name: 'gti_alerta_instabilidade_cliente', label: 'Alerta de instabilidade', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}', '{produto}'] },
|
||||||
|
{ name: 'gti_aviso_pendente_usuario', label: 'Aviso pendente usuario', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}', '{produto}'] },
|
||||||
|
{ name: 'gti_chamado_em_andamento', label: 'Chamado em andamento', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}', '{produto}'] },
|
||||||
|
{ name: 'confirma_suporte', label: 'Confirma suporte', language: 'pt_BR', route: 'templateBody', variables: ['{empresa}'] }
|
||||||
|
];
|
||||||
|
|
||||||
|
function defaultVariable(index) {
|
||||||
|
if (index === 0) return '{empresa}';
|
||||||
|
if (index === 1) return '{produto}';
|
||||||
|
return 'Informacao';
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTemplate(raw) {
|
||||||
|
const name = raw?.name || raw?.templateName || raw?.elementName;
|
||||||
|
if (!name || typeof name !== 'string') return null;
|
||||||
|
const language = raw?.language || raw?.languageCode || raw?.lang || raw?.locale || 'pt_BR';
|
||||||
|
const category = raw?.category || raw?.templateCategory || '';
|
||||||
|
const bodyComponent = Array.isArray(raw?.components)
|
||||||
|
? raw.components.find((component) => String(component?.type || '').toUpperCase() === 'BODY')
|
||||||
|
: null;
|
||||||
|
const text = raw?.text || raw?.body || raw?.content || raw?.templateText || bodyComponent?.text || '';
|
||||||
|
const matches = String(text).match(/{{\s*\d+\s*}}/g) || [];
|
||||||
|
const count = Math.max(...matches.map((match) => Number(match.replace(/\D/g, ''))), 0);
|
||||||
|
const variables = Array.from({ length: count }, (_, index) => defaultVariable(index));
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
label: raw?.label || raw?.title || name,
|
||||||
|
language,
|
||||||
|
category,
|
||||||
|
status: raw?.status || raw?.templateStatus || '',
|
||||||
|
route: String(category).toUpperCase() === 'MARKETING' ? 'templateMarketingBody' : 'templateBody',
|
||||||
|
variables,
|
||||||
|
text
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectTemplates(value, out = []) {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
for (const item of value) collectTemplates(item, out);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (!value || typeof value !== 'object') return out;
|
||||||
|
const normalized = normalizeTemplate(value);
|
||||||
|
if (normalized) out.push(normalized);
|
||||||
|
for (const child of Object.values(value)) {
|
||||||
|
if (child && typeof child === 'object') collectTemplates(child, out);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqueByName(templates) {
|
||||||
|
const map = new Map();
|
||||||
|
for (const template of templates) {
|
||||||
|
if (!template?.name) continue;
|
||||||
|
const count = Math.max(
|
||||||
|
Array.isArray(template.variables) ? template.variables.length : 0,
|
||||||
|
...((String(template.text || '').match(/{{\s*\d+\s*}}/g) || []).map((match) => Number(match.replace(/\D/g, '')))),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
template.variables = Array.from({ length: count }, (_, index) => String(template.variables?.[index] || '').trim() || defaultVariable(index));
|
||||||
|
map.set(`${template.name}:${template.language || 'pt_BR'}`, template);
|
||||||
|
}
|
||||||
|
return [...map.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listWabaTemplateLibrary(db) {
|
||||||
|
let synced = [];
|
||||||
|
try {
|
||||||
|
synced = JSON.parse(getSetting(db, 'gchat.wabaTemplatesJson', '[]'));
|
||||||
|
} catch {
|
||||||
|
synced = [];
|
||||||
|
}
|
||||||
|
return uniqueByName([...DEFAULT_WABA_TEMPLATES, ...synced]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function syncWabaTemplateLibrary(db) {
|
||||||
|
const url = getSetting(db, 'gchat.templatesUrl', '').trim();
|
||||||
|
const token = getSetting(db, 'gchat.bearerToken', '').trim().replace(/^Bearer\s+/i, '');
|
||||||
|
if (!url) {
|
||||||
|
return { ok: false, erro: 'configure gchat.templatesUrl com a URL de listagem de templates do GChat' };
|
||||||
|
}
|
||||||
|
const headers = { accept: 'application/json' };
|
||||||
|
if (token) headers.authorization = `Bearer ${token}`;
|
||||||
|
const response = await fetch(url, { headers });
|
||||||
|
const text = await response.text();
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
return { ok: false, erro: `GChat retornou resposta nao-JSON (${response.status})` };
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
return { ok: false, erro: `GChat templates falhou (${response.status}): ${JSON.stringify(data).slice(0, 300)}` };
|
||||||
|
}
|
||||||
|
const templates = uniqueByName(collectTemplates(data));
|
||||||
|
setSetting(db, 'gchat.wabaTemplatesJson', JSON.stringify(templates));
|
||||||
|
setSetting(db, 'gchat.templatesLastSync', new Date().toISOString());
|
||||||
|
return { ok: true, total: templates.length, templates };
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
import { envString } from '../env.mjs';
|
||||||
|
import { getSetting } from '../db.mjs';
|
||||||
|
|
||||||
|
// Cliente fino para a API externa do Z-PRO (docs/referencia/Z-PRO.postman_collection.json).
|
||||||
|
// Todas as rotas: POST/GET https://{BaseUrl}/v2/api/external/{ApiID}/<acao>, auth Bearer.
|
||||||
|
// Credenciais vem da tela de Configuracoes > Credenciais Z-PRO (tabela settings,
|
||||||
|
// editavel sem reiniciar o servidor) — se estiverem vazias la, cai pro .env
|
||||||
|
// (ZPRO_BASE_URL/ZPRO_API_ID/ZPRO_BEARER_TOKEN/ZPRO_WHATSAPP_ID), util pra
|
||||||
|
// deploy via variavel de ambiente (Docker/Proxmox) sem depender da tela.
|
||||||
|
|
||||||
|
// Aceita tanto "seu-dominio.com.br" quanto "https://seu-dominio.com.br/" (o
|
||||||
|
// que o usuario colar) — sem isso, colar a URL com protocolo virava
|
||||||
|
// "https://https://..." na hora de montar a chamada e todo teste falhava.
|
||||||
|
function normalizeBaseUrl(value) {
|
||||||
|
return value.trim().replace(/^https?:\/\//i, '').replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeBearerToken(value) {
|
||||||
|
return String(value || '').trim().replace(/^Bearer\s+/i, '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTicketId(data) {
|
||||||
|
if (data?.data?.ticketId) return String(data.data.ticketId);
|
||||||
|
if (data?.data?.id) return String(data.data.id);
|
||||||
|
|
||||||
|
const message = data?.data?.message;
|
||||||
|
if (typeof message === 'string') {
|
||||||
|
const jsonStart = message.indexOf('{');
|
||||||
|
if (jsonStart !== -1) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(message.slice(jsonStart));
|
||||||
|
if (parsed?.id) return String(parsed.id);
|
||||||
|
if (parsed?.ticketId) return String(parsed.ticketId);
|
||||||
|
} catch {
|
||||||
|
// Algumas respostas do Z-PRO embutem JSON em texto livre; se falhar,
|
||||||
|
// seguimos sem ticketId em vez de rejeitar uma chamada bem-sucedida.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeTemplateRoute(route) {
|
||||||
|
const allowed = new Set(['template', 'templateBody', 'templateMarketingBody']);
|
||||||
|
return allowed.has(route) ? route : 'template';
|
||||||
|
}
|
||||||
|
|
||||||
|
function config(db) {
|
||||||
|
const fromDbOrEnv = (settingKey, envKey) => {
|
||||||
|
const fromDb = db ? getSetting(db, settingKey, '') : '';
|
||||||
|
return fromDb || envString(envKey, '');
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
baseUrl: normalizeBaseUrl(fromDbOrEnv('zpro.baseUrl', 'ZPRO_BASE_URL')),
|
||||||
|
apiId: fromDbOrEnv('zpro.apiId', 'ZPRO_API_ID'),
|
||||||
|
bearerToken: normalizeBearerToken(fromDbOrEnv('zpro.bearerToken', 'ZPRO_BEARER_TOKEN')),
|
||||||
|
whatsappId: fromDbOrEnv('zpro.whatsappId', 'ZPRO_WHATSAPP_ID')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function zproDiagnostics(db) {
|
||||||
|
const { baseUrl, apiId, bearerToken, whatsappId } = config(db);
|
||||||
|
return {
|
||||||
|
baseUrl: baseUrl || '',
|
||||||
|
apiId: apiId ? `${apiId.slice(0, 8)}...` : '',
|
||||||
|
token: bearerToken ? `${bearerToken.slice(0, 4)}...${bearerToken.slice(-4)} (${bearerToken.length} chars)` : '',
|
||||||
|
whatsappId: whatsappId || '',
|
||||||
|
configured: Boolean(baseUrl && apiId && bearerToken),
|
||||||
|
hasWhatsappId: Boolean(whatsappId)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function zproConfigured(db) {
|
||||||
|
const { baseUrl, apiId, bearerToken } = config(db);
|
||||||
|
return Boolean(baseUrl && apiId && bearerToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function call(db, action, { method = 'POST', body, query } = {}) {
|
||||||
|
const { baseUrl, apiId, bearerToken } = config(db);
|
||||||
|
if (!baseUrl || !apiId || !bearerToken) {
|
||||||
|
throw new Error('Z-PRO nao configurado: preencha as credenciais em Configuracoes > Credenciais Z-PRO (ou ZPRO_BASE_URL/ZPRO_API_ID/ZPRO_BEARER_TOKEN no .env)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const path = action ? `${apiId}/${action}` : apiId;
|
||||||
|
const url = new URL(`https://${baseUrl}/v2/api/external/${path}`);
|
||||||
|
if (query) {
|
||||||
|
for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
authorization: `Bearer ${bearerToken}`,
|
||||||
|
'content-type': 'application/json'
|
||||||
|
},
|
||||||
|
body: method === 'GET' ? undefined : JSON.stringify(body ?? {})
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let data;
|
||||||
|
try {
|
||||||
|
data = text ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
data = { raw: text };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const apiError = data?.error || data?.message || data?.erro || '';
|
||||||
|
if (response.status === 401 || response.status === 403 || apiError === 'ERR_SESSION_NOT_AUTH_TOKEN') {
|
||||||
|
throw new Error([
|
||||||
|
`Z-PRO recusou a autenticacao (${response.status}${apiError ? ` / ${apiError}` : ''}).`,
|
||||||
|
'Confira se o Token e o API ID sao os de Admin > API do Z-PRO, nao o token de sessao/login.',
|
||||||
|
'Depois clique em "Testar conexao" antes de enviar mensagem.'
|
||||||
|
].join(' '));
|
||||||
|
}
|
||||||
|
if (apiError === 'ERR_SEND_TEMPLATE') {
|
||||||
|
throw new Error('Z-PRO recusou o template (ERR_SEND_TEMPLATE). Confirme se o API ID pertence ao mesmo canal WABA onde o template foi aprovado, se o idioma esta correto e se todas as variaveis do template foram preenchidas.');
|
||||||
|
}
|
||||||
|
throw new Error(`Z-PRO ${action} falhou (${response.status}): ${JSON.stringify(data).slice(0, 500)}`);
|
||||||
|
}
|
||||||
|
if (data?.success === false || data?.error) {
|
||||||
|
const apiError = data?.error || data?.message || data?.erro || '';
|
||||||
|
if (apiError === 'ERR_SEND_TEMPLATE') {
|
||||||
|
throw new Error('Z-PRO recusou o template (ERR_SEND_TEMPLATE). Confirme se o API ID pertence ao mesmo canal WABA onde o template foi aprovado, se o idioma esta correto e se todas as variaveis do template foram preenchidas.');
|
||||||
|
}
|
||||||
|
throw new Error(`Z-PRO ${action} falhou: ${JSON.stringify(data).slice(0, 500)}`);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cliente com as credenciais (settings + fallback .env) resolvidas uma vez e
|
||||||
|
// presas via closure — assim cada chamada do lote de outreach ja usa as
|
||||||
|
// credenciais atuais da tela de Configuracoes, sem precisar reiniciar o servidor.
|
||||||
|
export function createZproClient(db) {
|
||||||
|
return {
|
||||||
|
// Manda uma unica mensagem de texto pronta para um numero (docs: bulkIndividual).
|
||||||
|
// externalKey permite correlacionar a resposta/webhook do Z-PRO com o envio.
|
||||||
|
bulkIndividual({ number, message, externalKey }) {
|
||||||
|
const { whatsappId } = config(db);
|
||||||
|
return call(db, 'bulkIndividual', { body: { whatsappId, number, message, externalKey } });
|
||||||
|
},
|
||||||
|
|
||||||
|
sendText({ number, message, externalKey, isClosed = false }) {
|
||||||
|
return call(db, '', { body: { body: message, number, externalKey, isClosed, validateNumber: true } });
|
||||||
|
},
|
||||||
|
|
||||||
|
async createTicket({ number, message, externalKey, userId, channelId, queueId, status = 'pending' }) {
|
||||||
|
const body = {
|
||||||
|
body: message,
|
||||||
|
number,
|
||||||
|
externalKey,
|
||||||
|
userId: Number(userId),
|
||||||
|
status,
|
||||||
|
validateNumber: true
|
||||||
|
};
|
||||||
|
if (channelId) body.channelId = Number(channelId);
|
||||||
|
if (queueId) body.queueId = Number(queueId);
|
||||||
|
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await call(db, 'createTicket', { body });
|
||||||
|
} catch (error) {
|
||||||
|
if (!channelId || !String(error.message || '').includes('createTicket falhou')) throw error;
|
||||||
|
const fallbackBody = { ...body };
|
||||||
|
delete fallbackBody.channelId;
|
||||||
|
response = await call(db, 'createTicket', { body: fallbackBody });
|
||||||
|
}
|
||||||
|
return { ...response, ticketId: parseTicketId(response) };
|
||||||
|
},
|
||||||
|
|
||||||
|
listTags({ isActive = true } = {}) {
|
||||||
|
return call(db, 'listTags', { method: 'GET', query: { isActive: String(isActive) } });
|
||||||
|
},
|
||||||
|
|
||||||
|
createTag({ tag, color = '#2A78D6', isActive = true }) {
|
||||||
|
return call(db, 'createTag', { body: { tag, color, isActive } });
|
||||||
|
},
|
||||||
|
|
||||||
|
addTagContact({ number, tagIds }) {
|
||||||
|
return call(db, 'addTagContact', { body: { number, tagIds, validateNumber: true } });
|
||||||
|
},
|
||||||
|
|
||||||
|
// Manda um template ja aprovado no Meta Business Manager (canal oficial/WABA).
|
||||||
|
// Diferente de bulkIndividual: nao aceita texto livre, so nome+idioma de um
|
||||||
|
// template que ja existe e ja foi aprovado (a aprovacao e feita fora do app).
|
||||||
|
sendTemplateWaba({ number, templateName, languageCode = 'pt_BR', route = 'template', variables = [] }) {
|
||||||
|
const template = { name: templateName, language: { code: languageCode } };
|
||||||
|
const bodyParameters = variables
|
||||||
|
.filter((value) => value !== undefined && value !== null && String(value).trim() !== '')
|
||||||
|
.map((value) => ({ type: 'text', text: String(value) }));
|
||||||
|
|
||||||
|
if (bodyParameters.length) {
|
||||||
|
template.components = [{ type: 'body', parameters: bodyParameters }];
|
||||||
|
}
|
||||||
|
|
||||||
|
return call(db, normalizeTemplateRoute(route), {
|
||||||
|
body: {
|
||||||
|
number,
|
||||||
|
isClosed: false,
|
||||||
|
validateNumber: true,
|
||||||
|
templateData: {
|
||||||
|
messaging_product: 'whatsapp',
|
||||||
|
to: number,
|
||||||
|
type: 'template',
|
||||||
|
template
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import { registerExtractionRoutes } from './routes/extractions.mjs';
|
|||||||
import { registerLeadRoutes } from './routes/leads.mjs';
|
import { registerLeadRoutes } from './routes/leads.mjs';
|
||||||
import { registerExportRoutes } from './routes/exports.mjs';
|
import { registerExportRoutes } from './routes/exports.mjs';
|
||||||
import { registerAuthRoutes } from './routes/auth.mjs';
|
import { registerAuthRoutes } from './routes/auth.mjs';
|
||||||
|
import { registerOutreachRoutes } from './routes/outreach.mjs';
|
||||||
import { getCookie, getSession, SESSION_COOKIE } from './session.mjs';
|
import { getCookie, getSession, SESSION_COOKIE } from './session.mjs';
|
||||||
|
|
||||||
const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/health']);
|
const PUBLIC_API_PATHS = new Set(['/api/auth/login', '/api/health']);
|
||||||
@@ -53,6 +54,7 @@ export function createAppServer({ db, jobs, log = () => {} }) {
|
|||||||
registerExtractionRoutes(router, deps);
|
registerExtractionRoutes(router, deps);
|
||||||
registerLeadRoutes(router, deps);
|
registerLeadRoutes(router, deps);
|
||||||
registerExportRoutes(router, deps);
|
registerExportRoutes(router, deps);
|
||||||
|
registerOutreachRoutes(router, deps);
|
||||||
|
|
||||||
// SSE de progresso dos jobs (rota especial: gerencia a resposta manualmente)
|
// SSE de progresso dos jobs (rota especial: gerencia a resposta manualmente)
|
||||||
router.add('GET', '/api/jobs/:jobId/events', async (req, res, { params }) => {
|
router.add('GET', '/api/jobs/:jobId/events', async (req, res, { params }) => {
|
||||||
|
|||||||
@@ -9,7 +9,15 @@ import { cleanText } from '../../lead-engine.mjs';
|
|||||||
// Senha de confirmacao para a limpeza total da base (acao destrutiva e
|
// Senha de confirmacao para a limpeza total da base (acao destrutiva e
|
||||||
// irreversivel) — pedida no modal de Configuracoes antes de zerar leads,
|
// irreversivel) — pedida no modal de Configuracoes antes de zerar leads,
|
||||||
// exportacoes, capturas e extracoes. Vem do .env (nunca versionado).
|
// exportacoes, capturas e extracoes. Vem do .env (nunca versionado).
|
||||||
const RESET_BASE_PASSWORD = process.env.GTI_RESET_PASSWORD;
|
// Funcao (nao const) de proposito: os imports deste arquivo rodam antes do
|
||||||
|
// "await loadDotEnv()" em scripts/servidor.mjs (imports sao hoisted acima de
|
||||||
|
// qualquer top-level await), entao ler process.env.GTI_RESET_PASSWORD direto
|
||||||
|
// num const no topo do modulo sempre capturava undefined — nenhuma senha
|
||||||
|
// nunca batia, mesmo a correta. Lendo dentro da rota (call-time) o .env ja
|
||||||
|
// foi carregado quando a chamada realmente acontece.
|
||||||
|
function resetBasePassword() {
|
||||||
|
return process.env.GTI_RESET_PASSWORD;
|
||||||
|
}
|
||||||
|
|
||||||
function extractedCsvForUf(uf) {
|
function extractedCsvForUf(uf) {
|
||||||
const candidates = [
|
const candidates = [
|
||||||
@@ -125,9 +133,14 @@ export function registerMetaRoutes(router, { db, jobs }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Zera toda a base de leads (irreversivel): exige a senha de confirmacao.
|
// Zera toda a base de leads (irreversivel): exige a senha de confirmacao.
|
||||||
|
// 403 (nao 401): o usuario ja esta autenticado, so a senha de confirmacao
|
||||||
|
// da acao esta errada. 401 aqui disparava o redirect global de "sessao
|
||||||
|
// expirada" do api.js antes do erro aparecer na tela — o usuario via a
|
||||||
|
// tela de login e achava que so tinha caido a sessao, sem saber que a
|
||||||
|
// limpeza nunca rodou.
|
||||||
router.add('POST', '/api/admin/reset', async (req, res, { json, body }) => {
|
router.add('POST', '/api/admin/reset', async (req, res, { json, body }) => {
|
||||||
if (!body || body.senha !== RESET_BASE_PASSWORD) {
|
if (!body || body.senha !== resetBasePassword()) {
|
||||||
json(401, { erro: 'senha incorreta' });
|
json(403, { erro: 'senha incorreta' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { getSetting, listMessageTemplates, updateMessageTemplate } from '../../db.mjs';
|
||||||
|
import { createZproClient, zproConfigured, zproDiagnostics } from '../../outreach/zpro-client.mjs';
|
||||||
|
import { listWabaTemplateLibrary, syncWabaTemplateLibrary } from '../../outreach/waba-template-library.mjs';
|
||||||
|
import { COMMERCIAL_VARIABLES, renderTemplate } from '../../outreach/templates.mjs';
|
||||||
|
import { validatePhone, onlyDigits } from '../../scoring.mjs';
|
||||||
|
|
||||||
|
function dailyLimitStatus(db) {
|
||||||
|
const limite = Number(getSetting(db, 'outreach.mensagensPorDia', '10')) || 0;
|
||||||
|
const enviadosHoje = db.prepare(
|
||||||
|
"SELECT COUNT(*) AS t FROM outreach_sends WHERE status = 'enviado' AND date(sent_at) = date('now')"
|
||||||
|
).get().t;
|
||||||
|
|
||||||
|
return { limite, enviadosHoje, restante: Math.max(0, limite - enviadosHoje) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerOutreachRoutes(router, { db }) {
|
||||||
|
router.add('GET', '/api/outreach/status', async (req, res, { json }) => {
|
||||||
|
const ativo = getSetting(db, 'outreach.ativo', 'false') === 'true';
|
||||||
|
const { limite, enviadosHoje, restante } = dailyLimitStatus(db);
|
||||||
|
|
||||||
|
const porProduto = db.prepare(
|
||||||
|
`SELECT produto, COUNT(*) AS total
|
||||||
|
FROM outreach_sends
|
||||||
|
WHERE status = 'enviado' AND date(sent_at) = date('now')
|
||||||
|
GROUP BY produto ORDER BY total DESC`
|
||||||
|
).all();
|
||||||
|
|
||||||
|
// LEFT JOIN (nao JOIN): envio manual nao tem lead_id, senao sumiria da lista.
|
||||||
|
const ultimos = db.prepare(
|
||||||
|
`SELECT outreach_sends.id, outreach_sends.produto, outreach_sends.status,
|
||||||
|
outreach_sends.sent_at, outreach_sends.canal, outreach_sends.origem,
|
||||||
|
outreach_sends.numero, outreach_sends.erro, leads.empresa, leads.cidade
|
||||||
|
FROM outreach_sends LEFT JOIN leads ON leads.id = outreach_sends.lead_id
|
||||||
|
ORDER BY outreach_sends.id DESC LIMIT 20`
|
||||||
|
).all();
|
||||||
|
|
||||||
|
json(200, {
|
||||||
|
ativo,
|
||||||
|
configurado: zproConfigured(db),
|
||||||
|
mensagensPorDia: limite,
|
||||||
|
enviadosHoje,
|
||||||
|
restante,
|
||||||
|
porProduto,
|
||||||
|
ultimos
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Testa as credenciais Z-PRO atuais (settings ou .env) com uma chamada real
|
||||||
|
// e barata (listTags), sem mandar nenhuma mensagem — pra validar a tela de
|
||||||
|
// Credenciais Z-PRO antes de ativar a automacao de verdade.
|
||||||
|
router.add('POST', '/api/outreach/testar-conexao', async (req, res, { json }) => {
|
||||||
|
if (!zproConfigured(db)) {
|
||||||
|
json(400, { ok: false, erro: 'preencha Base URL, API ID e Token antes de testar', diagnostico: zproDiagnostics(db) });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await createZproClient(db).listTags({ isActive: true });
|
||||||
|
json(200, { ok: true, diagnostico: zproDiagnostics(db) });
|
||||||
|
} catch (error) {
|
||||||
|
json(200, { ok: false, erro: String(error.message || error), diagnostico: zproDiagnostics(db) });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Envio avulso pra um numero especifico, fora do lote automatico e sem
|
||||||
|
// depender de um lead cadastrado — util pra mandar uma mensagem pontual
|
||||||
|
// ou testar um template antes de ligar a automacao pra valer. Fica
|
||||||
|
// registrado em outreach_sends com origem='manual' (lead_id/produto
|
||||||
|
// ficam vazios), aparece nos "ultimos" igual aos envios automaticos.
|
||||||
|
router.add('POST', '/api/outreach/enviar-manual', async (req, res, { json, body }) => {
|
||||||
|
const numeroDigitado = String(body?.numero || '').trim();
|
||||||
|
if (!numeroDigitado) {
|
||||||
|
json(400, { erro: 'informe o numero (com DDI+DDD, ex.: 5511999999999)' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// O Z-PRO aceita (200 OK) numero mal formatado e so falha depois, de forma
|
||||||
|
// assincrona, sem avisar o app — por isso valida aqui ANTES de mandar,
|
||||||
|
// em vez de confiar na resposta da API pra saber se o numero e valido.
|
||||||
|
const { valid, motivo } = validatePhone(numeroDigitado);
|
||||||
|
if (!valid) {
|
||||||
|
json(400, { erro: `numero invalido (${motivo}): use DDI+DDD+numero, so digitos, ex. 5511999999999` });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const numero = onlyDigits(numeroDigitado);
|
||||||
|
const canal = body?.canal === 'oficial' ? 'oficial' : 'nao_oficial';
|
||||||
|
const mensagem = String(body?.mensagem || '').trim();
|
||||||
|
const templateWabaNome = String(body?.templateWabaNome || '').trim();
|
||||||
|
const templateWabaIdioma = String(body?.templateWabaIdioma || 'pt_BR').trim() || 'pt_BR';
|
||||||
|
const templateRoute = String(body?.templateRota || 'template').trim() || 'template';
|
||||||
|
const rawTemplateVariables = Array.isArray(body?.templateVariaveis)
|
||||||
|
? body.templateVariaveis.map((value) => String(value || '').trim()).filter(Boolean)
|
||||||
|
: [String(body?.templateVariavel1 || '').trim()].filter(Boolean);
|
||||||
|
const leadContext = body?.lead && typeof body.lead === 'object' ? body.lead : {};
|
||||||
|
const templateVariables = rawTemplateVariables.map((value) => renderTemplate(value, {
|
||||||
|
empresa: 'Gustavo',
|
||||||
|
produto: 'Atendimento comercial',
|
||||||
|
cidade: 'Salvador',
|
||||||
|
segmento_label: 'Suporte',
|
||||||
|
email: 'cliente@exemplo.com.br',
|
||||||
|
...leadContext,
|
||||||
|
whatsapp: leadContext.whatsapp || onlyDigits(numeroDigitado)
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (canal === 'nao_oficial' && !mensagem) {
|
||||||
|
json(400, { erro: 'escreva a mensagem pro canal nao-oficial' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (canal === 'oficial' && !templateWabaNome) {
|
||||||
|
json(400, { erro: 'informe o nome do template aprovado pro canal oficial' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { limite, enviadosHoje, restante } = dailyLimitStatus(db);
|
||||||
|
if (restante <= 0) {
|
||||||
|
json(429, {
|
||||||
|
ok: false,
|
||||||
|
erro: `limite diario atingido (${enviadosHoje}/${limite}). Aumente o limite por dia ou aguarde virar o dia.`,
|
||||||
|
limite,
|
||||||
|
enviadosHoje,
|
||||||
|
restante
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const insert = db.prepare(
|
||||||
|
`INSERT INTO outreach_sends (lead_id, produto, numero, mensagem_enviada, status, erro, zpro_ticket_id, canal, origem)
|
||||||
|
VALUES (NULL, '', ?, ?, ?, ?, ?, ?, 'manual')`
|
||||||
|
);
|
||||||
|
const mensagemEnviada = canal === 'oficial' ? `template:${templateWabaNome}/${templateWabaIdioma}` : mensagem;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const zproClient = createZproClient(db);
|
||||||
|
const externalKey = `gti-manual-${Date.now()}`;
|
||||||
|
const resposta = canal === 'oficial'
|
||||||
|
? await zproClient.sendTemplateWaba({
|
||||||
|
number: numero,
|
||||||
|
templateName: templateWabaNome,
|
||||||
|
languageCode: templateWabaIdioma,
|
||||||
|
route: templateRoute,
|
||||||
|
variables: templateVariables
|
||||||
|
})
|
||||||
|
: await zproClient.sendText({ number: numero, message: mensagem, externalKey });
|
||||||
|
const ticketId = resposta?.ticketId || resposta?.data?.ticketId ? String(resposta.ticketId || resposta.data.ticketId) : null;
|
||||||
|
insert.run(numero, mensagemEnviada, 'enviado', null, ticketId, canal);
|
||||||
|
json(200, { ok: true, ticketId });
|
||||||
|
} catch (error) {
|
||||||
|
insert.run(numero, mensagemEnviada, 'erro', String(error.message || error), null, canal);
|
||||||
|
json(200, { ok: false, erro: String(error.message || error) });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.add('GET', '/api/outreach/templates', async (req, res, { json }) => {
|
||||||
|
json(200, { templates: listMessageTemplates(db) });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.add('GET', '/api/outreach/waba-templates', async (req, res, { json }) => {
|
||||||
|
const syncUrl = getSetting(db, 'gchat.templatesUrl', '').trim();
|
||||||
|
const lastSync = getSetting(db, 'gchat.templatesLastSync', '');
|
||||||
|
const lastSyncAgeMs = lastSync ? Date.now() - new Date(lastSync).getTime() : Infinity;
|
||||||
|
if (syncUrl && lastSyncAgeMs > 10 * 60 * 1000) {
|
||||||
|
try {
|
||||||
|
await syncWabaTemplateLibrary(db);
|
||||||
|
} catch {
|
||||||
|
// A biblioteca local continua funcionando mesmo se o GChat estiver fora.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
json(200, {
|
||||||
|
templates: listWabaTemplateLibrary(db),
|
||||||
|
lastSync: getSetting(db, 'gchat.templatesLastSync', '')
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
router.add('GET', '/api/outreach/variables', async (req, res, { json }) => {
|
||||||
|
json(200, { variables: COMMERCIAL_VARIABLES });
|
||||||
|
});
|
||||||
|
|
||||||
|
router.add('POST', '/api/outreach/waba-templates/sync', async (req, res, { json }) => {
|
||||||
|
try {
|
||||||
|
json(200, await syncWabaTemplateLibrary(db));
|
||||||
|
} catch (error) {
|
||||||
|
json(200, { ok: false, erro: String(error.message || error) });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.add('PUT', '/api/outreach/templates/:produto', async (req, res, { json, params, body }) => {
|
||||||
|
const produto = params.produto;
|
||||||
|
if (!body || typeof body !== 'object') {
|
||||||
|
json(400, { erro: 'corpo JSON esperado: {"mensagem": "...", "ativo": true}' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const atualizado = updateMessageTemplate(db, produto, {
|
||||||
|
mensagem: body.mensagem,
|
||||||
|
ativo: body.ativo,
|
||||||
|
canal: body.canal,
|
||||||
|
templateWabaNome: body.templateWabaNome,
|
||||||
|
templateWabaIdioma: body.templateWabaIdioma,
|
||||||
|
templateWabaVariaveis: body.templateWabaVariaveis
|
||||||
|
});
|
||||||
|
if (!atualizado) {
|
||||||
|
json(404, { erro: `template do produto "${produto}" nao encontrado` });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
json(200, atualizado);
|
||||||
|
});
|
||||||
|
}
|
||||||
+17
-1
@@ -1,6 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, createLeadInserter, transaction, getSetting, setSetting, seedSegments, seedMunicipios, seedGeoCache, seedSettings } from '../src/db.mjs';
|
import { openDb, createLeadInserter, transaction, getSetting, setSetting, seedSegments, seedMunicipios, seedGeoCache, seedSettings, seedMessageTemplates, updateMessageTemplate } from '../src/db.mjs';
|
||||||
|
|
||||||
function sampleLead(overrides = {}) {
|
function sampleLead(overrides = {}) {
|
||||||
return {
|
return {
|
||||||
@@ -90,6 +90,22 @@ test('settings: get/set e seed com defaults Z-PRO', () => {
|
|||||||
db.close();
|
db.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('message_templates salva variaveis WABA automaticas por produto', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
|
||||||
|
const updated = updateMessageTemplate(db, 'ERP', {
|
||||||
|
canal: 'oficial',
|
||||||
|
templateWabaNome: 'gti_inicio_atendimento_solicitado',
|
||||||
|
templateWabaIdioma: 'pt_BR',
|
||||||
|
templateWabaVariaveis: ['{empresa}', 'Assunto: {produto}', '']
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(updated.template_waba_nome, 'gti_inicio_atendimento_solicitado');
|
||||||
|
assert.deepEqual(JSON.parse(updated.template_waba_variaveis_json), ['{empresa}', 'Assunto: {produto}']);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
test('seeds de segments, municipios e geo_cache', () => {
|
test('seeds de segments, municipios e geo_cache', () => {
|
||||||
const db = openDb(':memory:');
|
const db = openDb(':memory:');
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, setSetting } from '../src/db.mjs';
|
||||||
|
import { createRouter } from '../src/server/router.mjs';
|
||||||
|
import { registerOutreachRoutes } from '../src/server/routes/outreach.mjs';
|
||||||
|
|
||||||
|
function setupRouter(db) {
|
||||||
|
const router = createRouter();
|
||||||
|
registerOutreachRoutes(router, { db });
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeJson() {
|
||||||
|
const calls = [];
|
||||||
|
const json = (status, data) => calls.push({ status, data });
|
||||||
|
return { json, calls };
|
||||||
|
}
|
||||||
|
|
||||||
|
function configurarCredenciais(db) {
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'exemplo.zpro.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-teste');
|
||||||
|
}
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual exige numero', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
await handler(null, null, { json, body: { numero: '', mensagem: 'oi' } });
|
||||||
|
|
||||||
|
assert.equal(calls[0].status, 400);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual rejeita numero mal formatado antes de chamar o Z-PRO', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let fetchChamado = false;
|
||||||
|
global.fetch = async () => { fetchChamado = true; return { ok: true, text: async () => '{}' }; };
|
||||||
|
try {
|
||||||
|
await handler(null, null, { json, body: { numero: '55759990917800', canal: 'nao_oficial', mensagem: 'oi' } });
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(calls[0].status, 400);
|
||||||
|
assert.match(calls[0].data.erro, /numero invalido/);
|
||||||
|
assert.equal(fetchChamado, false);
|
||||||
|
assert.equal(db.prepare('SELECT COUNT(*) c FROM outreach_sends').get().c, 0);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual manda texto livre (nao-oficial) e registra origem=manual', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
global.fetch = async () => ({ ok: true, text: async () => JSON.stringify({ data: { ticketId: 999 } }) });
|
||||||
|
try {
|
||||||
|
await handler(null, null, { json, body: { numero: '5511999990001', canal: 'nao_oficial', mensagem: 'Oi, tudo bem?' } });
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(calls[0], { status: 200, data: { ok: true, ticketId: '999' } });
|
||||||
|
const row = db.prepare('SELECT * FROM outreach_sends').get();
|
||||||
|
assert.equal(row.origem, 'manual');
|
||||||
|
assert.equal(row.lead_id, null);
|
||||||
|
assert.equal(row.numero, '5511999990001');
|
||||||
|
assert.equal(row.mensagem_enviada, 'Oi, tudo bem?');
|
||||||
|
assert.equal(row.canal, 'nao_oficial');
|
||||||
|
assert.equal(row.zpro_ticket_id, '999');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual bloqueia quando limite diario acabou', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
setSetting(db, 'outreach.mensagensPorDia', '1');
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO outreach_sends (lead_id, produto, numero, mensagem_enviada, status, canal, origem)
|
||||||
|
VALUES (NULL, '', '5511999990001', 'ja enviado', 'enviado', 'nao_oficial', 'manual')`
|
||||||
|
).run();
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let fetchChamado = false;
|
||||||
|
global.fetch = async () => { fetchChamado = true; return { ok: true, text: async () => '{}' }; };
|
||||||
|
try {
|
||||||
|
await handler(null, null, { json, body: { numero: '5511999990002', canal: 'nao_oficial', mensagem: 'Oi' } });
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(calls[0].status, 429);
|
||||||
|
assert.equal(calls[0].data.ok, false);
|
||||||
|
assert.match(calls[0].data.erro, /limite diario atingido/);
|
||||||
|
assert.equal(fetchChamado, false);
|
||||||
|
assert.equal(db.prepare('SELECT COUNT(*) c FROM outreach_sends').get().c, 1);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual canal oficial exige nome do template', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
await handler(null, null, { json, body: { numero: '5511999990001', canal: 'oficial' } });
|
||||||
|
|
||||||
|
assert.equal(calls[0].status, 400);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual canal oficial envia multiplas variaveis do template', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let payload;
|
||||||
|
global.fetch = async (url, options) => {
|
||||||
|
payload = JSON.parse(options.body);
|
||||||
|
return { ok: true, status: 200, text: async () => '{"success":true,"data":{"ticketId":321}}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await handler(null, null, {
|
||||||
|
json,
|
||||||
|
body: {
|
||||||
|
numero: '5511999990001',
|
||||||
|
canal: 'oficial',
|
||||||
|
templateWabaNome: 'gti_inicio_atendimento_solicitado',
|
||||||
|
templateWabaIdioma: 'pt_BR',
|
||||||
|
templateVariaveis: ['Gustavo', 'Chamado #123', '']
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(calls[0], { status: 200, data: { ok: true, ticketId: '321' } });
|
||||||
|
assert.deepEqual(payload.templateData.template.components, [
|
||||||
|
{ type: 'body', parameters: [{ type: 'text', text: 'Gustavo' }, { type: 'text', text: 'Chamado #123' }] }
|
||||||
|
]);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual resolve variaveis internas do GChat', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let payload;
|
||||||
|
global.fetch = async (url, options) => {
|
||||||
|
payload = JSON.parse(options.body);
|
||||||
|
return { ok: true, status: 200, text: async () => '{"success":true,"data":{"ticketId":321}}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await handler(null, null, {
|
||||||
|
json,
|
||||||
|
body: {
|
||||||
|
numero: '5511999990001',
|
||||||
|
canal: 'oficial',
|
||||||
|
templateWabaNome: 'gti_teste',
|
||||||
|
templateWabaIdioma: 'pt_BR',
|
||||||
|
templateVariaveis: ['{{name}}', '{{protocol}}', '{{phoneNumber}}']
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(payload.templateData.template.components, [
|
||||||
|
{ type: 'body', parameters: [
|
||||||
|
{ type: 'text', text: 'Gustavo' },
|
||||||
|
{ type: 'text', text: 'Atendimento comercial' },
|
||||||
|
{ type: 'text', text: '5511999990001' }
|
||||||
|
] }
|
||||||
|
]);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('POST /api/outreach/enviar-manual registra erro quando o Z-PRO falha', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
configurarCredenciais(db);
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('POST', '/api/outreach/enviar-manual');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
global.fetch = async () => ({ ok: false, status: 400, text: async () => '{"erro":"numero nao existe no whatsapp"}' });
|
||||||
|
try {
|
||||||
|
await handler(null, null, { json, body: { numero: '5511999990001', canal: 'nao_oficial', mensagem: 'teste' } });
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(calls[0].data.ok, false);
|
||||||
|
const row = db.prepare('SELECT * FROM outreach_sends').get();
|
||||||
|
assert.equal(row.status, 'erro');
|
||||||
|
assert.match(row.erro, /numero nao existe/);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/outreach/status inclui envios manuais em "ultimos" (LEFT JOIN, sem lead)', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO outreach_sends (lead_id, produto, numero, mensagem_enviada, status, canal, origem)
|
||||||
|
VALUES (NULL, '', '5511999990001', 'oi', 'enviado', 'nao_oficial', 'manual')`
|
||||||
|
).run();
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('GET', '/api/outreach/status');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
await handler(null, null, { json });
|
||||||
|
|
||||||
|
const ultimo = calls[0].data.ultimos[0];
|
||||||
|
assert.equal(ultimo.origem, 'manual');
|
||||||
|
assert.equal(ultimo.numero, '5511999990001');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET /api/outreach/variables lista variaveis comerciais', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const router = setupRouter(db);
|
||||||
|
const { handler } = router.match('GET', '/api/outreach/variables');
|
||||||
|
const { json, calls } = fakeJson();
|
||||||
|
|
||||||
|
await handler(null, null, { json });
|
||||||
|
|
||||||
|
assert.equal(calls[0].status, 200);
|
||||||
|
assert.ok(calls[0].data.variables.some((variable) => variable.key === 'empresa'));
|
||||||
|
assert.ok(calls[0].data.variables.some((variable) => variable.key === 'name'));
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, createLeadInserter, setSetting, seedMessageTemplates, updateMessageTemplate } from '../src/db.mjs';
|
||||||
|
import { renderTemplate } from '../src/outreach/templates.mjs';
|
||||||
|
import { runOutreachBatch } from '../src/outreach/run.mjs';
|
||||||
|
|
||||||
|
function baseLead(overrides) {
|
||||||
|
return {
|
||||||
|
legal_name: '', ddd: '', email: '', segmento: '', segmento_label: '',
|
||||||
|
interesse: '', cnpj: '', cnae: '', endereco: '', website: '', pains_json: '[]',
|
||||||
|
origem: 'cnpj-base', telefone_valido: 1, cnpj_valido: 0, empresa_valida: 1,
|
||||||
|
score: 80, classificacao: 'bom', motivo_classificacao: '', capture_run_id: null,
|
||||||
|
captured_at: null, exported_at: null, prioridade: 1,
|
||||||
|
produtos_json: JSON.stringify([{ nome: 'ERP', estrelas: 5 }, { nome: 'G-Chat', estrelas: 3 }]),
|
||||||
|
produto_principal: 'ERP',
|
||||||
|
...overrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// libera a checagem de horario comercial em qualquer hora que o teste rode
|
||||||
|
function ativarOutreach(db, extra = {}) {
|
||||||
|
setSetting(db, 'outreach.ativo', 'true');
|
||||||
|
setSetting(db, 'outreach.horaInicio', '00:00');
|
||||||
|
setSetting(db, 'outreach.horaFim', '23:59');
|
||||||
|
setSetting(db, 'outreach.mensagensPorDia', '1');
|
||||||
|
setSetting(db, 'outreach.tentarProximoProduto', 'false');
|
||||||
|
setSetting(db, 'outreach.diasEntreProdutos', '5');
|
||||||
|
for (const [key, value] of Object.entries(extra)) setSetting(db, key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeZproClient(overrides = {}) {
|
||||||
|
const calls = { sendText: [], bulkIndividual: [], addTagContact: [], createTag: [], sendTemplateWaba: [] };
|
||||||
|
return {
|
||||||
|
calls,
|
||||||
|
sendText: async (args) => {
|
||||||
|
calls.sendText.push(args);
|
||||||
|
return { data: { ticketId: 123 } };
|
||||||
|
},
|
||||||
|
bulkIndividual: async (args) => {
|
||||||
|
calls.sendText.push(args);
|
||||||
|
return { data: { ticketId: 123 } };
|
||||||
|
},
|
||||||
|
sendTemplateWaba: async (args) => {
|
||||||
|
calls.sendTemplateWaba.push(args);
|
||||||
|
return { data: { ticketId: 456 } };
|
||||||
|
},
|
||||||
|
listTags: async () => ({ data: [] }),
|
||||||
|
createTag: async (args) => {
|
||||||
|
calls.createTag.push(args);
|
||||||
|
return { id: calls.createTag.length };
|
||||||
|
},
|
||||||
|
addTagContact: async (args) => {
|
||||||
|
calls.addTagContact.push(args);
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
...overrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('renderTemplate substitui {empresa}/{cidade}/{segmento}', () => {
|
||||||
|
const lead = { empresa: 'Padaria Sol', cidade: 'Ilheus', segmento_label: 'Padarias' };
|
||||||
|
const texto = renderTemplate('Ola {empresa} de {cidade} ({segmento})', lead);
|
||||||
|
assert.equal(texto, 'Ola Padaria Sol de Ilheus (Padarias)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renderTemplate usa fallback quando o lead nao tem o campo', () => {
|
||||||
|
const texto = renderTemplate('Ola {empresa} de {cidade}', {});
|
||||||
|
assert.equal(texto, 'Ola sua empresa de sua regiao');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renderTemplate substitui {produto}', () => {
|
||||||
|
const texto = renderTemplate('Oferta: {produto}', { produto: 'ERP' });
|
||||||
|
assert.equal(texto, 'Oferta: ERP');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renderTemplate substitui variaveis internas do GChat', () => {
|
||||||
|
const texto = renderTemplate('{{greeting}} {{name}} {{protocol}} {{businessName}} {{phoneNumber}} {{user}}', {
|
||||||
|
empresa: 'Padaria Sol', produto: 'ERP', whatsapp: '5511999990001'
|
||||||
|
});
|
||||||
|
assert.equal(texto, 'Ola Padaria Sol ERP Padaria Sol 5511999990001 Grupo GTI');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch nao faz nada quando outreach.ativo=false', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
setSetting(db, 'outreach.ativo', 'false');
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.deepEqual(resumo, { tentados: 0, enviados: 0, erros: 0, pulados: 0 });
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch manda o produto principal, registra o envio e aplica tags', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'Padaria Sol', whatsapp: '5511999990001', cidade: 'Ilheus', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP', 'G-Chat']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.enviados, 1);
|
||||||
|
assert.equal(resumo.erros, 0);
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 1);
|
||||||
|
assert.equal(zproClient.calls.sendText[0].number, '5511999990001');
|
||||||
|
assert.match(zproClient.calls.sendText[0].message, /Padaria Sol/);
|
||||||
|
assert.equal(zproClient.calls.addTagContact.length, 1);
|
||||||
|
assert.deepEqual(zproClient.calls.addTagContact[0].number, '5511999990001');
|
||||||
|
|
||||||
|
const row = db.prepare("SELECT * FROM outreach_sends WHERE status = 'enviado'").get();
|
||||||
|
assert.equal(row.produto, 'ERP');
|
||||||
|
assert.equal(row.lead_id, 1);
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch nao manda de novo o mesmo produto pro mesmo lead (mesmo com orcamento sobrando)', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
// ja existe um envio 'enviado' pra esse lead+produto, simulando uma rodada anterior
|
||||||
|
// (sem chamar runOutreachBatch de novo, que dispararia o intervalo real de 3-8s).
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO outreach_sends (lead_id, produto, mensagem_enviada, status) VALUES (1, 'ERP', 'msg', 'enviado')`
|
||||||
|
).run();
|
||||||
|
setSetting(db, 'outreach.mensagensPorDia', '10');
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
assert.equal(resumo.enviados, 0);
|
||||||
|
assert.equal(resumo.pulados, 1);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch ignora leads ja exportados', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({
|
||||||
|
lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA',
|
||||||
|
exported_at: new Date().toISOString()
|
||||||
|
}));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.enviados, 0);
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch respeita o limite diario', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
setSetting(db, 'outreach.mensagensPorDia', '0');
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.deepEqual(resumo, { tentados: 0, enviados: 0, erros: 0, pulados: 0 });
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch pula lead cujo template do produto esta inativo', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
updateMessageTemplate(db, 'ERP', { ativo: false });
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.enviados, 0);
|
||||||
|
assert.equal(resumo.pulados, 1);
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch registra erro e segue quando o Z-PRO falha', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient({
|
||||||
|
sendText: async () => {
|
||||||
|
throw new Error('falha simulada');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.erros, 1);
|
||||||
|
assert.equal(resumo.enviados, 0);
|
||||||
|
const row = db.prepare("SELECT * FROM outreach_sends WHERE status = 'erro'").get();
|
||||||
|
assert.match(row.erro, /falha simulada/);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch usa sendTemplateWaba (nao texto livre) quando o canal e oficial', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
updateMessageTemplate(db, 'ERP', {
|
||||||
|
canal: 'oficial',
|
||||||
|
templateWabaNome: 'promo_erp',
|
||||||
|
templateWabaIdioma: 'pt_BR',
|
||||||
|
templateWabaVariaveis: ['{empresa}', 'Assunto: {produto} em {cidade}']
|
||||||
|
});
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.enviados, 1);
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
assert.equal(zproClient.calls.sendTemplateWaba.length, 1);
|
||||||
|
assert.deepEqual(zproClient.calls.sendTemplateWaba[0], {
|
||||||
|
number: '5511999990001', templateName: 'promo_erp', languageCode: 'pt_BR', variables: ['A', 'Assunto: ERP em Salvador']
|
||||||
|
});
|
||||||
|
|
||||||
|
const row = db.prepare("SELECT * FROM outreach_sends WHERE status = 'enviado'").get();
|
||||||
|
assert.equal(row.canal, 'oficial');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch pula lead quando o canal e oficial mas o template nao foi configurado', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
updateMessageTemplate(db, 'ERP', { canal: 'oficial' }); // sem templateWabaNome
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
const resumo = await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
assert.equal(resumo.enviados, 0);
|
||||||
|
assert.equal(resumo.pulados, 1);
|
||||||
|
assert.equal(zproClient.calls.sendTemplateWaba.length, 0);
|
||||||
|
assert.equal(zproClient.calls.sendText.length, 0);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runOutreachBatch grava canal=nao_oficial por padrao', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const insert = createLeadInserter(db);
|
||||||
|
insert(baseLead({ lead_uid: 'A', dedup_key: 'k1', empresa: 'A', whatsapp: '5511999990001', cidade: 'Salvador', uf: 'BA' }));
|
||||||
|
seedMessageTemplates(db, ['ERP']);
|
||||||
|
ativarOutreach(db);
|
||||||
|
|
||||||
|
const zproClient = fakeZproClient();
|
||||||
|
await runOutreachBatch({ db, zproClient, log: () => {} });
|
||||||
|
|
||||||
|
const row = db.prepare("SELECT * FROM outreach_sends WHERE status = 'enviado'").get();
|
||||||
|
assert.equal(row.canal, 'nao_oficial');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, getSetting, setSetting } from '../src/db.mjs';
|
||||||
|
import { listWabaTemplateLibrary, syncWabaTemplateLibrary } from '../src/outreach/waba-template-library.mjs';
|
||||||
|
|
||||||
|
test('listWabaTemplateLibrary retorna modelos padrao', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
const templates = listWabaTemplateLibrary(db);
|
||||||
|
assert.ok(templates.some((template) => template.name === 'gti_inicio_atendimento_solicitado'));
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('syncWabaTemplateLibrary importa templates de resposta do GChat', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'gchat.templatesUrl', 'https://gchat.example/templates');
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
global.fetch = async () => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
text: async () => JSON.stringify({
|
||||||
|
data: [{
|
||||||
|
name: 'novo_template',
|
||||||
|
language: 'pt_BR',
|
||||||
|
category: 'UTILITY',
|
||||||
|
components: [{ type: 'BODY', text: 'Ola {{1}}, assunto {{2}}' }]
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const result = await syncWabaTemplateLibrary(db);
|
||||||
|
assert.equal(result.ok, true);
|
||||||
|
assert.equal(result.total, 1);
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
const saved = JSON.parse(getSetting(db, 'gchat.wabaTemplatesJson'));
|
||||||
|
assert.deepEqual(saved[0].variables, ['{empresa}', '{produto}']);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, setSetting } from '../src/db.mjs';
|
||||||
|
import { zproConfigured, createZproClient } from '../src/outreach/zpro-client.mjs';
|
||||||
|
|
||||||
|
test('zproConfigured e false sem credenciais na tela nem no .env', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
delete process.env.ZPRO_BASE_URL;
|
||||||
|
delete process.env.ZPRO_API_ID;
|
||||||
|
delete process.env.ZPRO_BEARER_TOKEN;
|
||||||
|
assert.equal(zproConfigured(db), false);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('zproConfigured fica true com credenciais salvas na tela (settings)', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'exemplo.zpro.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-secreto');
|
||||||
|
assert.equal(zproConfigured(db), true);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('zpro.bearerToken vazio na tela cai pro ZPRO_BEARER_TOKEN do .env', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'exemplo.zpro.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
process.env.ZPRO_BEARER_TOKEN = 'token-do-env';
|
||||||
|
assert.equal(zproConfigured(db), true);
|
||||||
|
delete process.env.ZPRO_BEARER_TOKEN;
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valor preenchido na tela tem prioridade sobre o .env', () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'exemplo.zpro.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
process.env.ZPRO_BEARER_TOKEN = 'token-do-env';
|
||||||
|
assert.equal(zproConfigured(db), true);
|
||||||
|
delete process.env.ZPRO_BEARER_TOKEN;
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('baseUrl colado com https:// na frente nao vira URL duplicada (https://https://...)', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'https://apigchat.exemplo.com.br/');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let urlChamada;
|
||||||
|
global.fetch = async (url) => {
|
||||||
|
urlChamada = String(url);
|
||||||
|
return { ok: true, text: async () => '{}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await createZproClient(db).listTags();
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(urlChamada, 'https://apigchat.exemplo.com.br/v2/api/external/abc123/listTags?isActive=true');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('token colado com Bearer e normalizado antes de enviar', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'Bearer token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let authorization;
|
||||||
|
global.fetch = async (url, options) => {
|
||||||
|
authorization = options.headers.authorization;
|
||||||
|
return { ok: true, text: async () => '{}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await createZproClient(db).listTags();
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(authorization, 'Bearer token-da-tela');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('erro de auth do Z-PRO vira mensagem acionavel', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
global.fetch = async () => ({
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
text: async () => '{"error":"ERR_SESSION_NOT_AUTH_TOKEN"}'
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await assert.rejects(
|
||||||
|
() => createZproClient(db).listTags(),
|
||||||
|
/Token e o API ID sao os de Admin > API/
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('createTicket extrai ticketId de resposta com JSON embutido em message', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
global.fetch = async () => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
text: async () => JSON.stringify({
|
||||||
|
success: true,
|
||||||
|
data: { message: 'Ticket create successfully {"id":444202,"status":"pending"}', error: false }
|
||||||
|
})
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const resposta = await createZproClient(db).createTicket({
|
||||||
|
number: '5511999990001',
|
||||||
|
message: 'oi',
|
||||||
|
externalKey: 'teste',
|
||||||
|
userId: 15,
|
||||||
|
channelId: 207
|
||||||
|
});
|
||||||
|
assert.equal(resposta.ticketId, '444202');
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('createTicket tenta sem channelId quando Z-PRO rejeita o canal informado', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
const bodies = [];
|
||||||
|
global.fetch = async (url, options) => {
|
||||||
|
const body = JSON.parse(options.body);
|
||||||
|
bodies.push(body);
|
||||||
|
if (body.channelId) {
|
||||||
|
return { ok: false, status: 404, text: async () => '{"success":false,"error":true}' };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
text: async () => JSON.stringify({ success: true, data: { message: 'Ticket create successfully {"id":444206}' } })
|
||||||
|
};
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const resposta = await createZproClient(db).createTicket({
|
||||||
|
number: '5511999990001',
|
||||||
|
message: 'oi',
|
||||||
|
externalKey: 'teste',
|
||||||
|
userId: 15,
|
||||||
|
channelId: 207
|
||||||
|
});
|
||||||
|
assert.equal(resposta.ticketId, '444206');
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(bodies.length, 2);
|
||||||
|
assert.equal(bodies[0].channelId, 207);
|
||||||
|
assert.equal('channelId' in bodies[1], false);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sendTemplateWaba inclui multiplas variaveis no components.body.parameters', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let payload;
|
||||||
|
global.fetch = async (url, options) => {
|
||||||
|
payload = JSON.parse(options.body);
|
||||||
|
return { ok: true, status: 200, text: async () => '{"success":true,"data":{"ticketId":123}}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await createZproClient(db).sendTemplateWaba({
|
||||||
|
number: '5511999990001',
|
||||||
|
templateName: 'confirma_suporte',
|
||||||
|
languageCode: 'pt_BR',
|
||||||
|
variables: ['Gustavo', 'Chamado #123']
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(payload.templateData.template.components, [
|
||||||
|
{ type: 'body', parameters: [{ type: 'text', text: 'Gustavo' }, { type: 'text', text: 'Chamado #123' }] }
|
||||||
|
]);
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sendTemplateWaba permite escolher rota templateBody', async () => {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
setSetting(db, 'zpro.baseUrl', 'apigchat.exemplo.com.br');
|
||||||
|
setSetting(db, 'zpro.apiId', 'abc123');
|
||||||
|
setSetting(db, 'zpro.bearerToken', 'token-da-tela');
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
let urlChamada;
|
||||||
|
global.fetch = async (url) => {
|
||||||
|
urlChamada = String(url);
|
||||||
|
return { ok: true, status: 200, text: async () => '{"success":true}' };
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await createZproClient(db).sendTemplateWaba({
|
||||||
|
number: '5511999990001',
|
||||||
|
templateName: 'confirma_suporte',
|
||||||
|
route: 'templateBody'
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(urlChamada, 'https://apigchat.exemplo.com.br/v2/api/external/abc123/templateBody');
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user