Add help icon and FAQ functionality
Implement a help icon with a "Fale com a gente" button, linking to an email form. Add admin functionality to create FAQs with text and image support, including a feedback mechanism.
This commit is contained in:
parent
e41618415d
commit
1d22b504a0
@ -1,3 +1,4 @@
|
||||
|
||||
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
@ -18,6 +19,7 @@ const GruposWhatsApp = lazy(() => import('./pages/GruposWhatsApp'));
|
||||
const NotFound = lazy(() => import('./pages/NotFound'));
|
||||
const CartoesCredito = lazy(() => import('./pages/CartoesCredito'));
|
||||
const Configuracoes = lazy(() => import('./pages/Configuracoes'));
|
||||
const AdminFAQ = lazy(() => import('./pages/AdminFAQ'));
|
||||
|
||||
function App() {
|
||||
const isLoggedIn = authStore((state) => state.isLoggedIn);
|
||||
@ -68,6 +70,7 @@ function App() {
|
||||
<Route path="/calendario" element={<ProtectedRoute><Suspense fallback={<div>Carregando...</div>}><Calendario /></Suspense></ProtectedRoute>} />
|
||||
<Route path="/whatsapp" element={<ProtectedRoute><Suspense fallback={<div>Carregando...</div>}><WhatsApp /></Suspense></ProtectedRoute>} />
|
||||
<Route path="/grupos-whatsapp" element={<ProtectedRoute><Suspense fallback={<div>Carregando...</div>}><GruposWhatsApp /></Suspense></ProtectedRoute>} />
|
||||
<Route path="/admin-faq" element={<ProtectedRoute><Suspense fallback={<div>Carregando...</div>}><AdminFAQ /></Suspense></ProtectedRoute>} />
|
||||
<Route path="/configuracoes" element={
|
||||
<ProtectedRoute>
|
||||
<Suspense fallback={<div className="flex items-center justify-center min-h-screen">Carregando...</div>}>
|
||||
|
||||
234
src/components/help/ContactForm.tsx
Normal file
234
src/components/help/ContactForm.tsx
Normal file
@ -0,0 +1,234 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { ArrowLeft, Upload, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
|
||||
interface ContactFormProps {
|
||||
onBack: () => void;
|
||||
}
|
||||
|
||||
const ContactForm = ({ onBack }: ContactFormProps) => {
|
||||
const [formData, setFormData] = useState({
|
||||
assunto: '',
|
||||
motivo: '',
|
||||
mensagem: '',
|
||||
anexo: null as File | null
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const motivosContato = [
|
||||
'Dúvida sobre funcionalidade',
|
||||
'Problema técnico',
|
||||
'Sugestão de melhoria',
|
||||
'Reclamação',
|
||||
'Elogio',
|
||||
'Outros'
|
||||
];
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formData.assunto || !formData.motivo || !formData.mensagem) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Por favor, preencha todos os campos obrigatórios.",
|
||||
variant: "destructive"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
let anexoUrl = null;
|
||||
|
||||
// Upload do anexo se existe
|
||||
if (formData.anexo) {
|
||||
const fileExt = formData.anexo.name.split('.').pop();
|
||||
const fileName = `${Date.now()}.${fileExt}`;
|
||||
|
||||
const { data: uploadData, error: uploadError } = await supabase.storage
|
||||
.from('anexos-contato')
|
||||
.upload(fileName, formData.anexo);
|
||||
|
||||
if (uploadError) throw uploadError;
|
||||
|
||||
const { data: { publicUrl } } = supabase.storage
|
||||
.from('anexos-contato')
|
||||
.getPublicUrl(fileName);
|
||||
|
||||
anexoUrl = publicUrl;
|
||||
}
|
||||
|
||||
// Salvar contato no banco
|
||||
const { error } = await supabase
|
||||
.from('contatos')
|
||||
.insert({
|
||||
assunto: formData.assunto,
|
||||
motivo: formData.motivo,
|
||||
mensagem: formData.mensagem,
|
||||
anexo_url: anexoUrl,
|
||||
user_id: (await supabase.auth.getUser()).data.user?.id,
|
||||
status: 'pendente'
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
toast({
|
||||
title: "Mensagem enviada!",
|
||||
description: "Você vai receber a resposta no e-mail que cadastrou aqui. Obrigado!",
|
||||
});
|
||||
|
||||
// Reset form
|
||||
setFormData({
|
||||
assunto: '',
|
||||
motivo: '',
|
||||
mensagem: '',
|
||||
anexo: null
|
||||
});
|
||||
|
||||
onBack();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erro ao enviar contato:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível enviar sua mensagem. Tente novamente.",
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
// Validar tamanho (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
toast({
|
||||
title: "Arquivo muito grande",
|
||||
description: "O arquivo deve ter no máximo 5MB.",
|
||||
variant: "destructive"
|
||||
});
|
||||
return;
|
||||
}
|
||||
setFormData({ ...formData, anexo: file });
|
||||
}
|
||||
};
|
||||
|
||||
const removeFile = () => {
|
||||
setFormData({ ...formData, anexo: null });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={onBack}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Você vai receber a resposta no e-mail que cadastrou aqui
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="assunto">Assunto *</Label>
|
||||
<Input
|
||||
id="assunto"
|
||||
placeholder="Digite o assunto da mensagem"
|
||||
value={formData.assunto}
|
||||
onChange={(e) => setFormData({ ...formData, assunto: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="motivo">Motivo do contato *</Label>
|
||||
<Select value={formData.motivo} onValueChange={(value) => setFormData({ ...formData, motivo: value })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Escolha o motivo do contato" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{motivosContato.map((motivo) => (
|
||||
<SelectItem key={motivo} value={motivo}>
|
||||
{motivo}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="mensagem">Mensagem *</Label>
|
||||
<Textarea
|
||||
id="mensagem"
|
||||
placeholder="Digite sua mensagem"
|
||||
value={formData.mensagem}
|
||||
onChange={(e) => setFormData({ ...formData, mensagem: e.target.value })}
|
||||
rows={5}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Anexo (opcional)</Label>
|
||||
{formData.anexo ? (
|
||||
<div className="flex items-center gap-2 p-3 border rounded-lg bg-gray-50">
|
||||
<span className="flex-1 text-sm">{formData.anexo.name}</span>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={removeFile}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="file"
|
||||
onChange={handleFileChange}
|
||||
accept="image/*,.pdf,.doc,.docx"
|
||||
className="hidden"
|
||||
id="file-upload"
|
||||
/>
|
||||
<Label
|
||||
htmlFor="file-upload"
|
||||
className="flex items-center gap-2 px-4 py-2 border rounded-md cursor-pointer hover:bg-gray-50"
|
||||
>
|
||||
<Upload className="h-4 w-4" />
|
||||
Envie uma imagem
|
||||
</Label>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Formatos aceitos: imagens, PDF, DOC, DOCX (máx. 5MB)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full bg-green-600 hover:bg-green-700"
|
||||
>
|
||||
{loading ? 'Enviando...' : 'Enviar mensagem'}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactForm;
|
||||
170
src/components/help/FAQList.tsx
Normal file
170
src/components/help/FAQList.tsx
Normal file
@ -0,0 +1,170 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ChevronDown, ChevronUp, ThumbsUp, ThumbsDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface FAQ {
|
||||
id: string;
|
||||
pergunta: string;
|
||||
resposta: string;
|
||||
imagem_url?: string;
|
||||
ativo: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const FAQList = () => {
|
||||
const [faqs, setFaqs] = useState<FAQ[]>([]);
|
||||
const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
loadFAQs();
|
||||
}, []);
|
||||
|
||||
const loadFAQs = async () => {
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('faqs')
|
||||
.select('*')
|
||||
.eq('ativo', true)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
setFaqs(data || []);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar FAQs:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível carregar as perguntas frequentes.",
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleExpanded = (id: string) => {
|
||||
const newExpanded = new Set(expandedItems);
|
||||
if (newExpanded.has(id)) {
|
||||
newExpanded.delete(id);
|
||||
} else {
|
||||
newExpanded.add(id);
|
||||
}
|
||||
setExpandedItems(newExpanded);
|
||||
};
|
||||
|
||||
const handleFeedback = async (faqId: string, helpful: boolean) => {
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('faq_feedback')
|
||||
.insert({
|
||||
faq_id: faqId,
|
||||
helpful: helpful,
|
||||
user_id: (await supabase.auth.getUser()).data.user?.id
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
toast({
|
||||
title: "Obrigado!",
|
||||
description: "Seu feedback foi registrado com sucesso.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Erro ao enviar feedback:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível registrar seu feedback.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const filteredFAQs = faqs.filter(faq =>
|
||||
faq.pergunta.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
faq.resposta.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-center py-8">Carregando perguntas frequentes...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Input
|
||||
placeholder="Buscar assunto..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full"
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
{filteredFAQs.map((faq) => (
|
||||
<div key={faq.id} className="border rounded-lg overflow-hidden">
|
||||
<button
|
||||
onClick={() => toggleExpanded(faq.id)}
|
||||
className="w-full px-4 py-3 text-left hover:bg-gray-50 flex items-center justify-between"
|
||||
>
|
||||
<span className="font-medium">{faq.pergunta}</span>
|
||||
{expandedItems.has(faq.id) ? (
|
||||
<ChevronUp className="h-5 w-5" />
|
||||
) : (
|
||||
<ChevronDown className="h-5 w-5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{expandedItems.has(faq.id) && (
|
||||
<div className="px-4 py-3 border-t bg-gray-50">
|
||||
<div className="space-y-3">
|
||||
<div dangerouslySetInnerHTML={{ __html: faq.resposta }} />
|
||||
|
||||
{faq.imagem_url && (
|
||||
<img
|
||||
src={faq.imagem_url}
|
||||
alt="Imagem de apoio"
|
||||
className="max-w-full h-auto rounded-lg"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 pt-3 border-t">
|
||||
<span className="text-sm text-gray-600">Esta resposta foi útil?</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleFeedback(faq.id, true)}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<ThumbsUp className="h-4 w-4" />
|
||||
Sim
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleFeedback(faq.id, false)}
|
||||
className="flex items-center gap-1"
|
||||
>
|
||||
<ThumbsDown className="h-4 w-4" />
|
||||
Não
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{filteredFAQs.length === 0 && (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
{searchTerm ? 'Nenhuma pergunta encontrada para sua busca.' : 'Nenhuma pergunta disponível no momento.'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FAQList;
|
||||
58
src/components/help/HelpIcon.tsx
Normal file
58
src/components/help/HelpIcon.tsx
Normal file
@ -0,0 +1,58 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { HelpCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import FAQList from './FAQList';
|
||||
import ContactForm from './ContactForm';
|
||||
|
||||
const HelpIcon = () => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showContact, setShowContact] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
className="fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-all z-50 bg-blue-600 text-white hover:bg-blue-700 border-0"
|
||||
onClick={() => setIsOpen(true)}
|
||||
>
|
||||
<HelpCircle className="h-6 w-6" />
|
||||
</Button>
|
||||
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-2xl">
|
||||
{showContact ? 'Fale Conosco' : 'Como podemos ajudar?'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{showContact ? (
|
||||
<ContactForm onBack={() => setShowContact(false)} />
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<FAQList />
|
||||
<div className="flex justify-center pt-4 border-t">
|
||||
<Button
|
||||
onClick={() => setShowContact(true)}
|
||||
className="bg-green-600 hover:bg-green-700 text-white px-8 py-3 rounded-lg"
|
||||
>
|
||||
Fale com a gente
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default HelpIcon;
|
||||
@ -2,6 +2,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import Sidebar from '@/components/layout/Sidebar';
|
||||
import Header from '@/components/layout/Header';
|
||||
import HelpIcon from '@/components/help/HelpIcon';
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { Menu } from 'lucide-react';
|
||||
import { Button } from "@/components/ui/button";
|
||||
@ -58,6 +59,9 @@ const Layout: React.FC<LayoutProps> = ({ children }) => {
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Help Icon */}
|
||||
<HelpIcon />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
392
src/pages/AdminFAQ.tsx
Normal file
392
src/pages/AdminFAQ.tsx
Normal file
@ -0,0 +1,392 @@
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, Edit, Trash2, Eye, EyeOff, BarChart3 } from 'lucide-react';
|
||||
import Layout from '@/components/layout/Layout';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
|
||||
interface FAQ {
|
||||
id: string;
|
||||
pergunta: string;
|
||||
resposta: string;
|
||||
imagem_url?: string;
|
||||
ativo: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const AdminFAQ = () => {
|
||||
const [faqs, setFaqs] = useState<FAQ[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [editingFaq, setEditingFaq] = useState<FAQ | null>(null);
|
||||
const [showStats, setShowStats] = useState(false);
|
||||
const [stats, setStats] = useState<any>({});
|
||||
const { toast } = useToast();
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
pergunta: '',
|
||||
resposta: '',
|
||||
imagem_url: '',
|
||||
ativo: true
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
loadFAQs();
|
||||
loadStats();
|
||||
}, []);
|
||||
|
||||
const loadFAQs = async () => {
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('faqs')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) throw error;
|
||||
setFaqs(data || []);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar FAQs:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível carregar os FAQs.",
|
||||
variant: "destructive"
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('faq_feedback')
|
||||
.select(`
|
||||
faq_id,
|
||||
helpful,
|
||||
faqs (pergunta)
|
||||
`);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
const statsData = data?.reduce((acc: any, feedback: any) => {
|
||||
const faqId = feedback.faq_id;
|
||||
if (!acc[faqId]) {
|
||||
acc[faqId] = {
|
||||
pergunta: feedback.faqs?.pergunta || 'FAQ não encontrado',
|
||||
helpful: 0,
|
||||
notHelpful: 0,
|
||||
total: 0
|
||||
};
|
||||
}
|
||||
|
||||
if (feedback.helpful) {
|
||||
acc[faqId].helpful++;
|
||||
} else {
|
||||
acc[faqId].notHelpful++;
|
||||
}
|
||||
acc[faqId].total++;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
setStats(statsData || {});
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar estatísticas:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formData.pergunta || !formData.resposta) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Pergunta e resposta são obrigatórias.",
|
||||
variant: "destructive"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (editingFaq) {
|
||||
const { error } = await supabase
|
||||
.from('faqs')
|
||||
.update(formData)
|
||||
.eq('id', editingFaq.id);
|
||||
|
||||
if (error) throw error;
|
||||
toast({ title: "FAQ atualizado com sucesso!" });
|
||||
} else {
|
||||
const { error } = await supabase
|
||||
.from('faqs')
|
||||
.insert(formData);
|
||||
|
||||
if (error) throw error;
|
||||
toast({ title: "FAQ criado com sucesso!" });
|
||||
}
|
||||
|
||||
resetForm();
|
||||
loadFAQs();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar FAQ:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível salvar o FAQ.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (faq: FAQ) => {
|
||||
setEditingFaq(faq);
|
||||
setFormData({
|
||||
pergunta: faq.pergunta,
|
||||
resposta: faq.resposta,
|
||||
imagem_url: faq.imagem_url || '',
|
||||
ativo: faq.ativo
|
||||
});
|
||||
setShowForm(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!confirm('Tem certeza que deseja excluir este FAQ?')) return;
|
||||
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('faqs')
|
||||
.delete()
|
||||
.eq('id', id);
|
||||
|
||||
if (error) throw error;
|
||||
toast({ title: "FAQ excluído com sucesso!" });
|
||||
loadFAQs();
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir FAQ:', error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Não foi possível excluir o FAQ.",
|
||||
variant: "destructive"
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleActive = async (id: string, ativo: boolean) => {
|
||||
try {
|
||||
const { error } = await supabase
|
||||
.from('faqs')
|
||||
.update({ ativo: !ativo })
|
||||
.eq('id', id);
|
||||
|
||||
if (error) throw error;
|
||||
toast({ title: `FAQ ${!ativo ? 'ativado' : 'desativado'} com sucesso!` });
|
||||
loadFAQs();
|
||||
} catch (error) {
|
||||
console.error('Erro ao alterar status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setFormData({
|
||||
pergunta: '',
|
||||
resposta: '',
|
||||
imagem_url: '',
|
||||
ativo: true
|
||||
});
|
||||
setEditingFaq(null);
|
||||
setShowForm(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">Gerenciar FAQs</h1>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowStats(true)}
|
||||
>
|
||||
<BarChart3 className="h-4 w-4 mr-2" />
|
||||
Estatísticas
|
||||
</Button>
|
||||
<Button onClick={() => setShowForm(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Novo FAQ
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Pergunta</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Data</TableHead>
|
||||
<TableHead>Ações</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{faqs.map((faq) => (
|
||||
<TableRow key={faq.id}>
|
||||
<TableCell className="max-w-md">
|
||||
<div className="truncate">{faq.pergunta}</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={faq.ativo ? "success" : "secondary"}>
|
||||
{faq.ativo ? 'Ativo' : 'Inativo'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{new Date(faq.created_at).toLocaleDateString('pt-BR')}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleEdit(faq)}
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleToggleActive(faq.id, faq.ativo)}
|
||||
>
|
||||
{faq.ativo ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(faq.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{/* Form Dialog */}
|
||||
<Dialog open={showForm} onOpenChange={setShowForm}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{editingFaq ? 'Editar FAQ' : 'Novo FAQ'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="pergunta">Pergunta *</Label>
|
||||
<Input
|
||||
id="pergunta"
|
||||
value={formData.pergunta}
|
||||
onChange={(e) => setFormData({ ...formData, pergunta: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="resposta">Resposta *</Label>
|
||||
<Textarea
|
||||
id="resposta"
|
||||
value={formData.resposta}
|
||||
onChange={(e) => setFormData({ ...formData, resposta: e.target.value })}
|
||||
rows={6}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="imagem_url">URL da Imagem (opcional)</Label>
|
||||
<Input
|
||||
id="imagem_url"
|
||||
type="url"
|
||||
value={formData.imagem_url}
|
||||
onChange={(e) => setFormData({ ...formData, imagem_url: e.target.value })}
|
||||
placeholder="https://exemplo.com/imagem.jpg"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="ativo"
|
||||
checked={formData.ativo}
|
||||
onChange={(e) => setFormData({ ...formData, ativo: e.target.checked })}
|
||||
/>
|
||||
<Label htmlFor="ativo">FAQ ativo</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button type="submit">
|
||||
{editingFaq ? 'Atualizar' : 'Criar'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={resetForm}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Stats Dialog */}
|
||||
<Dialog open={showStats} onOpenChange={setShowStats}>
|
||||
<DialogContent className="max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Estatísticas dos FAQs</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{Object.entries(stats).map(([faqId, data]: [string, any]) => (
|
||||
<div key={faqId} className="border rounded-lg p-4">
|
||||
<h3 className="font-medium mb-2">{data.pergunta}</h3>
|
||||
<div className="flex gap-4 text-sm">
|
||||
<span className="text-green-600">
|
||||
👍 Útil: {data.helpful} ({Math.round((data.helpful / data.total) * 100)}%)
|
||||
</span>
|
||||
<span className="text-red-600">
|
||||
👎 Não útil: {data.notHelpful} ({Math.round((data.notHelpful / data.total) * 100)}%)
|
||||
</span>
|
||||
<span className="text-gray-600">Total: {data.total}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{Object.keys(stats).length === 0 && (
|
||||
<p className="text-center text-gray-500 py-8">
|
||||
Nenhum feedback registrado ainda.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminFAQ;
|
||||
@ -48,8 +48,8 @@ const WhatsApp = () => {
|
||||
|
||||
const {
|
||||
hasExistingInstance,
|
||||
checkingInstance,
|
||||
instanceData,
|
||||
checkingExistingInstance,
|
||||
existingInstanceData,
|
||||
recheckInstance
|
||||
} = useExistingInstanceCheck(userEmail);
|
||||
|
||||
@ -83,7 +83,7 @@ const WhatsApp = () => {
|
||||
}
|
||||
};
|
||||
|
||||
if (checkingInstance || isLoading) {
|
||||
if (checkingExistingInstance || isLoading) {
|
||||
return (
|
||||
<Layout>
|
||||
<LoadingState message="Verificando suas instâncias..." />
|
||||
@ -97,12 +97,12 @@ const WhatsApp = () => {
|
||||
<WhatsAppHeader
|
||||
userEmail={userEmail}
|
||||
onRefresh={recheckInstance}
|
||||
isRefreshing={checkingInstance}
|
||||
isRefreshing={checkingExistingInstance}
|
||||
/>
|
||||
|
||||
<WhatsAppManager
|
||||
hasExistingInstance={hasExistingInstance}
|
||||
existingInstanceData={instanceData}
|
||||
existingInstanceData={existingInstanceData}
|
||||
instances={instances}
|
||||
isRefreshing={isRefreshing}
|
||||
activeInstance={activeInstance}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user