Refactor: Split ContactForm into smaller components

Refactors ContactForm.tsx into smaller, more manageable components for improved code organization and maintainability.
This commit is contained in:
gpt-engineer-app[bot] 2025-06-21 19:50:38 +00:00
parent c323023e28
commit 352bb9aa59
6 changed files with 341 additions and 395 deletions

View File

@ -1,19 +1,11 @@
import { useState } from 'react';
import { ArrowLeft, Upload, X } from 'lucide-react';
import { ArrowLeft } 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';
import ContactFormFields from './ContactFormFields';
import ContactFormHeader from './ContactFormHeader';
interface ContactFormProps {
onBack: () => void;
@ -29,15 +21,6 @@ const ContactForm = ({ onBack }: ContactFormProps) => {
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();
@ -75,7 +58,7 @@ const ContactForm = ({ onBack }: ContactFormProps) => {
// Salvar contato no banco
const { error } = await supabase
.from('contatos' as any)
.from('contatos')
.insert({
assunto: formData.assunto,
motivo: formData.motivo,
@ -114,119 +97,15 @@ const ContactForm = ({ onBack }: ContactFormProps) => {
}
};
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>
<ContactFormHeader onBack={onBack} />
<ContactFormFields
formData={formData}
setFormData={setFormData}
loading={loading}
onSubmit={handleSubmit}
/>
</div>
);
};

View File

@ -0,0 +1,120 @@
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 ContactFormFileUpload from './ContactFormFileUpload';
interface FormData {
assunto: string;
motivo: string;
mensagem: string;
anexo: File | null;
}
interface ContactFormFieldsProps {
formData: FormData;
setFormData: (data: FormData) => void;
loading: boolean;
onSubmit: (e: React.FormEvent) => void;
}
const ContactFormFields = ({ formData, setFormData, loading, onSubmit }: ContactFormFieldsProps) => {
const { toast } = useToast();
const motivosContato = [
'Dúvida sobre funcionalidade',
'Problema técnico',
'Sugestão de melhoria',
'Reclamação',
'Elogio',
'Outros'
];
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 (
<form onSubmit={onSubmit} 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>
<ContactFormFileUpload
anexo={formData.anexo}
onFileChange={handleFileChange}
onRemoveFile={removeFile}
/>
<Button
type="submit"
disabled={loading}
className="w-full bg-green-600 hover:bg-green-700"
>
{loading ? 'Enviando...' : 'Enviar mensagem'}
</Button>
</form>
);
};
export default ContactFormFields;

View File

@ -0,0 +1,49 @@
import { Upload, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
interface ContactFormFileUploadProps {
anexo: File | null;
onFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
onRemoveFile: () => void;
}
const ContactFormFileUpload = ({ anexo, onFileChange, onRemoveFile }: ContactFormFileUploadProps) => {
return (
<div className="space-y-2">
<Label>Anexo (opcional)</Label>
{anexo ? (
<div className="flex items-center gap-2 p-3 border rounded-lg bg-gray-50">
<span className="flex-1 text-sm">{anexo.name}</span>
<Button type="button" variant="ghost" size="sm" onClick={onRemoveFile}>
<X className="h-4 w-4" />
</Button>
</div>
) : (
<div className="flex items-center gap-2">
<Input
type="file"
onChange={onFileChange}
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>
);
};
export default ContactFormFileUpload;

View File

@ -0,0 +1,24 @@
import { ArrowLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
interface ContactFormHeaderProps {
onBack: () => void;
}
const ContactFormHeader = ({ onBack }: ContactFormHeaderProps) => {
return (
<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>
);
};
export default ContactFormHeader;

View File

@ -29,13 +29,13 @@ const FAQList = () => {
const loadFAQs = async () => {
try {
const { data, error } = await supabase
.from('faqs' as any)
.from('faqs')
.select('*')
.eq('ativo', true)
.order('created_at', { ascending: false });
if (error) throw error;
setFaqs((data as FAQ[]) || []);
setFaqs(data || []);
} catch (error) {
console.error('Erro ao carregar FAQs:', error);
toast({
@ -61,7 +61,7 @@ const FAQList = () => {
const handleFeedback = async (faqId: string, helpful: boolean) => {
try {
const { error } = await supabase
.from('faq_feedback' as any)
.from('faq_feedback')
.insert({
faq_id: faqId,
helpful: helpful,

View File

@ -1,28 +1,13 @@
import { useState, useEffect } from 'react';
import { Plus, Edit, Trash2, Eye, EyeOff, BarChart3 } from 'lucide-react';
import Layout from '@/components/layout/Layout';
import { Plus, Edit, Trash2, Eye, EyeOff } 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 {
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';
interface FAQ {
id: string;
@ -35,34 +20,29 @@ interface FAQ {
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
});
const [loading, setLoading] = useState(false);
const { toast } = useToast();
useEffect(() => {
loadFAQs();
loadStats();
}, []);
const loadFAQs = async () => {
try {
const { data, error } = await supabase
.from('faqs' as any)
.from('faqs')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
setFaqs((data as FAQ[]) || []);
setFaqs(data || []);
} catch (error) {
console.error('Erro ao carregar FAQs:', error);
toast({
@ -70,80 +50,36 @@ const AdminFAQ = () => {
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' as any)
.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;
}
setLoading(true);
try {
if (editingFaq) {
// Atualizar FAQ existente
const { error } = await supabase
.from('faqs' as any)
.from('faqs')
.update(formData)
.eq('id', editingFaq.id);
if (error) throw error;
toast({ title: "FAQ atualizado com sucesso!" });
} else {
// Criar novo FAQ
const { error } = await supabase
.from('faqs' as any)
.from('faqs')
.insert(formData);
if (error) throw error;
toast({ title: "FAQ criado com sucesso!" });
}
resetForm();
// Reset form
setFormData({ pergunta: '', resposta: '', imagem_url: '', ativo: true });
setEditingFaq(null);
loadFAQs();
} catch (error) {
console.error('Erro ao salvar FAQ:', error);
@ -152,6 +88,8 @@ const AdminFAQ = () => {
description: "Não foi possível salvar o FAQ.",
variant: "destructive"
});
} finally {
setLoading(false);
}
};
@ -163,7 +101,6 @@ const AdminFAQ = () => {
imagem_url: faq.imagem_url || '',
ativo: faq.ativo
});
setShowForm(true);
};
const handleDelete = async (id: string) => {
@ -171,7 +108,7 @@ const AdminFAQ = () => {
try {
const { error } = await supabase
.from('faqs' as any)
.from('faqs')
.delete()
.eq('id', id);
@ -188,204 +125,141 @@ const AdminFAQ = () => {
}
};
const handleToggleActive = async (id: string, ativo: boolean) => {
const toggleStatus = async (faq: FAQ) => {
try {
const { error } = await supabase
.from('faqs' as any)
.update({ ativo: !ativo })
.eq('id', id);
.from('faqs')
.update({ ativo: !faq.ativo })
.eq('id', faq.id);
if (error) throw error;
toast({ title: `FAQ ${!ativo ? 'ativado' : 'desativado'} com sucesso!` });
toast({ title: `FAQ ${!faq.ativo ? 'ativado' : 'desativado'} com sucesso!` });
loadFAQs();
} catch (error) {
console.error('Erro ao alterar status:', error);
toast({
title: "Erro",
description: "Não foi possível alterar o status do FAQ.",
variant: "destructive"
});
}
};
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="container mx-auto p-6 space-y-6">
<h1 className="text-3xl font-bold">Gerenciar FAQs</h1>
<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 ? "default" : "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>
{/* Formulário */}
<Card>
<CardHeader>
<CardTitle>{editingFaq ? 'Editar FAQ' : 'Criar Novo FAQ'}</CardTitle>
</CardHeader>
<CardContent>
<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>
{/* 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="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"
value={formData.imagem_url}
onChange={(e) => setFormData({ ...formData, imagem_url: e.target.value })}
placeholder="https://exemplo.com/imagem.jpg"
/>
</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}>
<div className="flex items-center gap-4">
<Button type="submit" disabled={loading}>
{loading ? 'Salvando...' : editingFaq ? 'Atualizar' : 'Criar'}
</Button>
{editingFaq && (
<Button
type="button"
variant="outline"
onClick={() => {
setEditingFaq(null);
setFormData({ pergunta: '', resposta: '', imagem_url: '', ativo: true });
}}
>
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>
</form>
</CardContent>
</Card>
{/* Lista de FAQs */}
<Card>
<CardHeader>
<CardTitle>FAQs Cadastrados</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{faqs.map((faq) => (
<div key={faq.id} className="border rounded-lg p-4">
<div className="flex items-start justify-between gap-4">
<div className="flex-1">
<h3 className="font-medium mb-2">{faq.pergunta}</h3>
<div
className="text-sm text-gray-600 mb-2"
dangerouslySetInnerHTML={{ __html: faq.resposta.substring(0, 200) + '...' }}
/>
<div className="flex items-center gap-2 text-xs text-gray-500">
<span>Status: {faq.ativo ? 'Ativo' : 'Inativo'}</span>
<span></span>
<span>{new Date(faq.created_at).toLocaleDateString()}</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => toggleStatus(faq)}
>
{faq.ativo ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleEdit(faq)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="sm"
onClick={() => handleDelete(faq.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
};