3042ddca38
- /wa-inbox, /wa-sessions e /wa-secretaria rodam sem a sidebar do scoreodonto (isStandaloneView); cada tela tem seu "Voltar" (Secretária ganhou botão na ThinNav). - SessionsView: banner "Você já possui acesso ao WhatsApp" quando há sessão ativa. - avatares: usa a URL do CDN (contactAvatarUrl/instance.avatar) direto; Avatar exibe sem depender de version; self-heal no onError re-busca a foto atual. - deps: framer-motion, immer. Dev override com HMR (docker-compose.dev.yml). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
199 lines
11 KiB
TypeScript
199 lines
11 KiB
TypeScript
import React, { useEffect, useState, useCallback } from 'react';
|
|
import { ShieldCheck, LayoutGrid, Check, Loader2, Tag, AlertTriangle, Briefcase } from 'lucide-react';
|
|
import { useAuthStore } from '../store/authStore';
|
|
|
|
interface SettingsPanelProps {
|
|
instanceId: string | null;
|
|
}
|
|
|
|
// Engines oferecidas no painel. A 'official' (Baileys 6, que dá 401) fica de fora.
|
|
// baileys7 → Baileys 7 oficial (a que conecta) → rótulo "API estável"
|
|
// infinite → InfinityAPI (com botões)
|
|
// titulo = rótulo genérico (todos os usuários). tituloTec = rótulo técnico
|
|
// (Baileys/Infinity), exibido apenas para admin/ruibto@gmail.com.
|
|
const ENGINES: {
|
|
value: string; titulo: string; tituloTec?: string; desc: string; icon: any;
|
|
iconCls: string; activeBorder: string; activeBg: string; checkCls: string; btnCls: string;
|
|
}[] = [
|
|
{
|
|
value: 'baileys7', titulo: 'API estável', tituloTec: 'API estável (Baileys 7)',
|
|
desc: 'Conexão recomendada do WhatsApp',
|
|
icon: ShieldCheck, iconCls: 'text-emerald-500',
|
|
activeBorder: 'border-emerald-400', activeBg: 'bg-emerald-50', checkCls: 'text-emerald-600',
|
|
btnCls: 'bg-emerald-500 hover:bg-emerald-600',
|
|
},
|
|
{
|
|
value: 'infinite', titulo: 'API com botões', tituloTec: 'InfinityAPI',
|
|
desc: 'Com botões interativos (experimental)',
|
|
icon: LayoutGrid, iconCls: 'text-amber-500',
|
|
activeBorder: 'border-amber-400', activeBg: 'bg-amber-50', checkCls: 'text-amber-600',
|
|
btnCls: 'bg-amber-500 hover:bg-amber-600',
|
|
},
|
|
];
|
|
|
|
export default function SettingsPanel({ instanceId }: SettingsPanelProps) {
|
|
const user = useAuthStore((s) => s.user);
|
|
// Termos técnicos (Baileys/Infinity) só para admin ou ruibto@gmail.com.
|
|
const canSeeTech = user?.role === 'ADMIN' || user?.email === 'ruibto@gmail.com';
|
|
const [engine, setEngine] = useState<string | null>(null);
|
|
const [isBusiness, setIsBusiness] = useState<boolean | null>(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const [saving, setSaving] = useState<string | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [version, setVersion] = useState<any>(null);
|
|
|
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8008';
|
|
const authHeader = (): Record<string, string> => {
|
|
const t = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
|
|
return t ? { Authorization: `Bearer ${t}` } : {};
|
|
};
|
|
|
|
// Versão do sistema (servida em /version.json)
|
|
useEffect(() => {
|
|
fetch('/version.json')
|
|
.then((r) => (r.ok ? r.json() : null))
|
|
.then(setVersion)
|
|
.catch(() => {});
|
|
}, []);
|
|
|
|
// Engine atual da instância
|
|
useEffect(() => {
|
|
if (!instanceId) return;
|
|
setLoading(true);
|
|
fetch(`${API_URL}/api/instances`, { headers: authHeader() })
|
|
.then((r) => (r.ok ? r.json() : []))
|
|
.then((list) => {
|
|
const inst = Array.isArray(list) ? list.find((i: any) => i.id === instanceId) : null;
|
|
setEngine(inst?.engine ?? null);
|
|
setIsBusiness(inst ? !!inst.isBusiness : null);
|
|
})
|
|
.catch(() => {})
|
|
.finally(() => setLoading(false));
|
|
}, [instanceId]);
|
|
|
|
const selectEngine = useCallback(async (value: string) => {
|
|
if (!instanceId || saving || value === engine) return;
|
|
// Trocar de engine invalida a sessão (credenciais não migram entre APIs):
|
|
// confirma porque exige escanear o QR Code novamente.
|
|
if (typeof window !== 'undefined' && !window.confirm(
|
|
'Trocar de API vai DESCONECTAR a sessão atual.\n\n' +
|
|
'Você precisará escanear o QR Code novamente para reconectar. Continuar?'
|
|
)) return;
|
|
setSaving(value);
|
|
setError(null);
|
|
try {
|
|
const res = await fetch(`${API_URL}/api/instances/${instanceId}/engine`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json', ...authHeader() },
|
|
body: JSON.stringify({ engine: value }),
|
|
});
|
|
if (res.status === 429) {
|
|
const d = await res.json().catch(() => ({}));
|
|
throw new Error(d.error ?? 'Aguarde o intervalo entre trocas.');
|
|
}
|
|
if (!res.ok) throw new Error('Falha ao trocar a API.');
|
|
setEngine(value);
|
|
} catch (e: any) {
|
|
setError(e?.message ?? 'Erro ao trocar a API.');
|
|
} finally {
|
|
setSaving(null);
|
|
}
|
|
}, [instanceId, saving, engine]);
|
|
|
|
return (
|
|
<div className="relative z-[1] flex-1 h-full overflow-y-auto bg-[#f0f2f5] p-6 md:p-10">
|
|
<div className="max-w-2xl mx-auto">
|
|
<h1 className="text-3xl font-light text-[#41525d] mb-2">Configurações</h1>
|
|
<p className="text-base text-[#667781] mb-4">Escolha a API de conexão do WhatsApp para esta instância.</p>
|
|
|
|
<div className="flex items-start gap-3 rounded-xl bg-amber-50 border border-amber-200 p-4 mb-6">
|
|
<AlertTriangle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
|
|
<p className="text-sm text-[#5b4b1f]">
|
|
Trocar de API <strong>desconecta a sessão</strong> — será necessário <strong>escanear o QR Code novamente</strong> para reconectar.
|
|
</p>
|
|
</div>
|
|
|
|
{!instanceId && (
|
|
<p className="text-base text-[#667781] mb-6">Selecione uma instância primeiro.</p>
|
|
)}
|
|
|
|
{/* ── Engines ─────────────────────────────────────────────── */}
|
|
<div className="flex flex-col gap-4 mb-6">
|
|
{ENGINES.map((opt) => {
|
|
const Icon = opt.icon;
|
|
const ativa = engine === opt.value;
|
|
const salvando = saving === opt.value;
|
|
return (
|
|
<div
|
|
key={opt.value}
|
|
className={`rounded-2xl border-2 bg-white p-8 transition-colors ${ativa ? `${opt.activeBorder} ${opt.activeBg}` : 'border-[#e9edef]'}`}
|
|
>
|
|
<div className="flex items-center gap-4">
|
|
<div className={`w-14 h-14 rounded-2xl flex items-center justify-center ${ativa ? 'bg-white' : 'bg-[#f0f2f5]'}`}>
|
|
<Icon className={`w-8 h-8 ${opt.iconCls}`} />
|
|
</div>
|
|
<div className="flex-1 min-w-0">
|
|
<h2 className="text-2xl font-semibold text-[#111b21]">{canSeeTech && opt.tituloTec ? opt.tituloTec : opt.titulo}</h2>
|
|
<p className="text-base text-[#667781]">{opt.desc}</p>
|
|
</div>
|
|
{ativa ? (
|
|
<span className={`flex items-center gap-1 font-medium text-lg ${opt.checkCls}`}>
|
|
<Check className="w-6 h-6" /> Ativa
|
|
</span>
|
|
) : (
|
|
<button
|
|
onClick={() => selectEngine(opt.value)}
|
|
disabled={!instanceId || !!saving}
|
|
className={`inline-flex items-center gap-2 rounded-xl text-white text-lg font-medium px-6 py-3 disabled:opacity-60 ${opt.btnCls}`}
|
|
>
|
|
{salvando ? <Loader2 className="w-5 h-5 animate-spin" /> : <Icon className="w-5 h-5" />}
|
|
Ativar
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{loading && <p className="text-sm text-[#8696a0] mb-4">Carregando configuração atual…</p>}
|
|
{error && <p className="text-sm text-red-500 mb-4">{error}</p>}
|
|
|
|
{/* ── Conta Business ──────────────────────────────────────── */}
|
|
<div className="rounded-2xl border-2 border-[#e9edef] bg-white p-8 mb-6">
|
|
<div className="flex items-center gap-4">
|
|
<div className="w-14 h-14 rounded-2xl bg-[#f0f2f5] flex items-center justify-center">
|
|
<Briefcase className="w-8 h-8 text-[#54656f]" />
|
|
</div>
|
|
<div className="flex-1">
|
|
<h2 className="text-2xl font-semibold text-[#111b21]">Conta Business</h2>
|
|
<p className="text-xl font-medium text-[#41525d] mt-1">
|
|
{isBusiness === null ? '—' : isBusiness ? 'Sim (WhatsApp Business)' : 'Não (conta pessoal)'}
|
|
</p>
|
|
<p className="text-xs text-[#8696a0] mt-1">
|
|
Business App ≠ Business API — botões só são garantidos na Business API oficial.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* ── Versão ──────────────────────────────────────────────── */}
|
|
<div className="rounded-2xl border-2 border-[#e9edef] bg-white p-8">
|
|
<div className="flex items-center gap-4">
|
|
<div className="w-14 h-14 rounded-2xl bg-[#f0f2f5] flex items-center justify-center">
|
|
<Tag className="w-8 h-8 text-[#54656f]" />
|
|
</div>
|
|
<div className="flex-1">
|
|
<h2 className="text-2xl font-semibold text-[#111b21]">Versão</h2>
|
|
<p className="text-3xl font-light text-[#41525d] mt-1">{version?.version ?? '—'}</p>
|
|
{version?.buildCount != null && (
|
|
<p className="text-base text-[#667781]">build {version.buildCount}</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|