Atualização para que possa mandar mesagens do Zap para grupos

This commit is contained in:
2026-08-25 00:41:26 -03:00
parent 7e093f3af8
commit 985e2e3b55
19 changed files with 971 additions and 494 deletions

View File

@@ -1,8 +1,27 @@
<%= form_with model: [:admin, contato], data: { turbo: false }, class: 'space-y-5' do |f| %>
<%
input = 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
focus:ring-[#f97316] transition-colors'
rotulo = 'block text-sm font-medium text-gray-300 mb-1.5'
ajuda = 'text-gray-500 text-xs mt-1.5'
toggle = "w-11 h-6 bg-gray-700 peer-focus:outline-none rounded-full peer
peer-checked:after:translate-x-full peer-checked:after:border-white
after:content-[''] after:absolute after:top-[2px] after:left-[2px]
after:bg-white after:border-gray-300 after:border after:rounded-full
after:h-5 after:w-5 after:transition-all peer-checked:bg-[#f97316]"
%>
<%= form_with model: [:admin, contato], data: { turbo: false },
class: 'bg-[#1a1a1a] rounded-2xl border border-white/5 p-8 space-y-6' do |f| %>
<% if contato.errors.any? %>
<div class="bg-red-500/10 border border-red-500/30 rounded-xl px-4 py-3 text-red-300 text-sm">
<div class="p-4 bg-red-900/30 border border-red-500/40 rounded-xl">
<p class="text-red-400 text-sm font-medium mb-2">
<%= pluralize(contato.errors.count, 'erro', 'erros') %> encontrado<%= contato.errors.count > 1 ? 's' : '' %>:
</p>
<ul class="list-disc list-inside space-y-1">
<% contato.errors.full_messages.each do |msg| %><li><%= msg %></li><% end %>
<% contato.errors.full_messages.each do |msg| %>
<li class="text-red-300 text-sm"><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
@@ -10,42 +29,46 @@
<%# Pessoa x grupo do WhatsApp. O JavaScript no fim troca os blocos; sem JS a
página continua utilizável — os dois blocos ficam visíveis e o model limpa
o que não pertence ao tipo escolhido. %>
<div data-tipo-contato>
<%= f.label :tipo, 'Tipo de destinatário', class: 'block text-gray-400 text-sm mb-1' %>
<%= f.select :tipo,
[['Pessoa (número ou e-mail)', 'pessoa'], ['Grupo do WhatsApp', 'grupo_whatsapp']], {},
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500',
id: 'contato-tipo' %>
</div>
<div>
<%= f.label :nome, class: 'block text-gray-400 text-sm mb-1' %>
<%= f.text_field :nome, required: true,
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500' %>
<p class="text-xs text-gray-500 mt-1">Como aparece nas listas e em <code>{{contato}}</code>.</p>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4" id="bloco-pessoa">
<div>
<%= f.label :telefone, 'WhatsApp', class: 'block text-gray-400 text-sm mb-1' %>
<%= f.text_field :telefone, placeholder: '(11) 92005-1157',
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500' %>
<p class="text-xs text-gray-500 mt-1">Pode digitar com máscara — é normalizado ao salvar.</p>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
<div data-tipo-contato>
<%= f.label :tipo, 'Tipo de destinatário', class: rotulo %>
<%= f.select :tipo,
[['Pessoa (número ou e-mail)', 'pessoa'], ['Grupo do WhatsApp', 'grupo_whatsapp']], {},
class: "#{input} cursor-pointer", id: 'contato-tipo' %>
</div>
<div>
<%= f.label :email, 'E-mail', class: 'block text-gray-400 text-sm mb-1' %>
<%= f.email_field :email,
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500' %>
<%= f.label :nome, class: rotulo %>
<%= f.text_field :nome, required: true, placeholder: 'Maria Souza', class: input %>
<p class="<%= ajuda %>">Como aparece nas listas e em <code class="font-mono text-[#f97316]">{{contato}}</code>.</p>
</div>
</div>
<%# ── Pessoa ──────────────────────────────────────────────── %>
<div id="bloco-pessoa" class="border-t border-white/5 pt-6">
<p class="text-sm font-medium text-gray-300 mb-4">Como falar com esta pessoa</p>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
<div>
<%= f.label :telefone, 'WhatsApp', class: rotulo %>
<%= f.text_field :telefone, placeholder: '(11) 92005-1157', class: input %>
<p class="<%= ajuda %>">Pode digitar com máscara — é normalizado ao salvar.</p>
</div>
<div>
<%= f.label :email, 'E-mail', class: rotulo %>
<%= f.email_field :email, placeholder: 'maria@empresa.com', class: input %>
<p class="<%= ajuda %>">Sem e-mail, este contato só recebe WhatsApp.</p>
</div>
</div>
</div>
<%# ── Grupo do WhatsApp ───────────────────────────────────── %>
<%# O identificador do grupo é opaco ("120363…@g.us") — digitar na mão é pedir
erro. A lista vem da ponte, com o número já conectado. %>
<div id="bloco-grupo" data-url="<%= grupos_whatsapp_admin_contatos_path %>">
<%= f.label :whatsapp_grupo_jid, 'Grupo do WhatsApp', class: 'block text-gray-400 text-sm mb-1' %>
<div class="flex gap-2">
<select id="grupo-jid" name="contato[whatsapp_grupo_jid]"
class="flex-1 bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500">
<div id="bloco-grupo" class="border-t border-white/5 pt-6"
data-url="<%= grupos_whatsapp_admin_contatos_path %>">
<p class="text-sm font-medium text-gray-300 mb-4">Qual grupo do WhatsApp</p>
<div class="flex flex-col sm:flex-row gap-3">
<select id="grupo-jid" name="contato[whatsapp_grupo_jid]" class="<%= input %> cursor-pointer flex-1">
<% if contato.whatsapp_grupo_jid.present? %>
<option value="<%= contato.whatsapp_grupo_jid %>" selected>
<%= contato.whatsapp_grupo_nome.presence || contato.whatsapp_grupo_jid %>
@@ -55,38 +78,53 @@
<% end %>
</select>
<button type="button" id="btn-carregar-grupos"
class="px-4 py-2.5 rounded-xl text-sm whitespace-nowrap bg-[#1a1a1a] text-gray-300 border border-white/10 hover:border-orange-500">
Buscar grupos
class="inline-flex items-center justify-center gap-2 px-6 py-3 border border-white/10
hover:border-white/20 text-gray-300 hover:text-white rounded-xl
transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50">
<%= icone :buscar, cor: nil, tamanho: 'w-4 h-4', espaco: false %>
<span data-btn-texto>Buscar grupos</span>
</button>
</div>
<%= f.hidden_field :whatsapp_grupo_nome, id: 'grupo-nome' %>
<p class="text-xs text-gray-500 mt-1" id="grupo-aviso">
<p class="<%= ajuda %>" id="grupo-aviso">
Só aparecem grupos em que o número conectado já é membro. Grupo com "somente
administradores" recusa o envio se o número não for admin.
</p>
</div>
<div>
<%= f.label :grupo_contato_id, 'Grupo', class: 'block text-gray-400 text-sm mb-1' %>
<%= f.collection_select :grupo_contato_id, @grupos, :id, :nome, { include_blank: 'Sem grupo (não recebe nada)' },
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500' %>
<p class="text-xs text-gray-500 mt-1">É o grupo que define quais eventos este contato recebe.</p>
<%# ── Assinatura e situação ───────────────────────────────── %>
<div class="border-t border-white/5 pt-6 space-y-6">
<div>
<%= f.label :grupo_contato_id, 'Grupo', class: rotulo %>
<%= f.collection_select :grupo_contato_id, @grupos, :id, :nome,
{ include_blank: 'Sem grupo (não recebe nada)' }, class: "#{input} cursor-pointer" %>
<p class="<%= ajuda %>">É o grupo que define quais eventos este contato recebe.</p>
</div>
<div>
<%= f.label :observacao, 'Observação', class: rotulo %>
<%= f.text_field :observacao, placeholder: 'Opcional', class: input %>
</div>
<div class="flex items-center">
<div class="flex-1">
<%= f.label :ativo, 'Contato ativo', class: 'block text-sm font-medium text-gray-300' %>
<p class="text-gray-500 text-xs mt-0.5">Contato inativo continua cadastrado, mas não recebe nada</p>
</div>
<label class="relative inline-flex items-center cursor-pointer ml-4">
<%= f.check_box :ativo, class: 'sr-only peer' %>
<div class="<%= toggle %>"></div>
</label>
</div>
</div>
<div>
<%= f.label :observacao, 'Observação', class: 'block text-gray-400 text-sm mb-1' %>
<%= f.text_field :observacao,
class: 'w-full bg-[#1a1a1a] border border-white/10 rounded-xl text-white text-sm px-3 py-2.5 focus:outline-none focus:border-orange-500' %>
</div>
<label class="flex items-center gap-2 text-sm text-gray-300">
<%= f.check_box :ativo, class: 'rounded border-white/20 bg-[#1a1a1a] text-orange-500' %>
Ativo
</label>
<div class="flex items-center gap-3">
<%= f.submit 'Salvar', class: 'px-4 py-2.5 rounded-xl text-sm font-semibold bg-orange-500 text-black hover:bg-orange-400 cursor-pointer' %>
<%= link_to 'Cancelar', admin_contatos_path, data: { turbo: false }, class: 'text-gray-400 hover:text-white text-sm' %>
<div class="flex items-center justify-between pt-2 border-t border-white/5">
<%= link_to 'Cancelar', admin_contatos_path, data: { turbo: false },
class: 'px-6 py-3 text-gray-400 hover:text-white border border-white/10
hover:border-white/20 rounded-xl transition-colors' %>
<%= f.submit contato.new_record? ? 'Criar Contato' : 'Salvar Alterações',
class: 'px-8 py-3 bg-[#f97316] hover:bg-orange-500 text-white font-semibold
rounded-xl transition-colors cursor-pointer min-h-[48px]' %>
</div>
<% end %>
@@ -101,6 +139,10 @@
var botao = document.getElementById('btn-carregar-grupos');
if (!tipo || !pessoa || !grupo) return;
// O rótulo do botão vive num <span> próprio: trocar o textContent do botão
// inteiro apagaria o ícone junto.
var botaoTexto = botao.querySelector('[data-btn-texto]');
function alternar() {
var ehGrupo = tipo.value === 'grupo_whatsapp';
pessoa.classList.toggle('hidden', ehGrupo);
@@ -109,6 +151,15 @@
tipo.addEventListener('change', alternar);
alternar();
// Estado do aviso: erro em vermelho, sucesso em verde, neutro em cinza —
// o texto sozinho não dizia se a busca deu certo.
function avisar(texto, estado) {
aviso.textContent = texto;
aviso.className = 'text-xs mt-1.5 ' + (
estado === 'erro' ? 'text-red-400' : estado === 'ok' ? 'text-green-400' : 'text-gray-500'
);
}
// O nome do grupo é gravado junto com o id: a tela precisa mostrar algo
// legível mesmo com a ponte fora do ar (o id sozinho não diz nada).
select.addEventListener('change', function () {
@@ -118,13 +169,13 @@
botao.addEventListener('click', function () {
botao.disabled = true;
botao.textContent = 'Buscando…';
botaoTexto.textContent = 'Buscando…';
fetch(grupo.dataset.url, { headers: { Accept: 'application/json' } })
.then(function (r) { return r.json(); })
.then(function (dados) {
if (dados.erro) { aviso.textContent = dados.erro; return; }
if (dados.erro) { avisar(dados.erro, 'erro'); return; }
if (!dados.grupos.length) {
aviso.textContent = 'Nenhum grupo encontrado — o número conectado não participa de nenhum.';
avisar('Nenhum grupo encontrado — o número conectado não participa de nenhum.', 'erro');
return;
}
select.innerHTML = '<option value="">— escolha —</option>';
@@ -138,10 +189,10 @@
o.textContent = g.nome + ' (' + g.participantes + ')' + alerta;
select.appendChild(o);
});
aviso.textContent = dados.grupos.length + ' grupo(s) encontrado(s).';
avisar(dados.grupos.length + ' grupo(s) encontrado(s) — escolha um acima.', 'ok');
})
.catch(function () { aviso.textContent = 'Não foi possível falar com a ponte do WhatsApp.'; })
.finally(function () { botao.disabled = false; botao.textContent = 'Buscar grupos'; });
.catch(function () { avisar('Não foi possível falar com a ponte do WhatsApp.', 'erro'); })
.finally(function () { botao.disabled = false; botaoTexto.textContent = 'Buscar grupos'; });
});
})();
</script>