import React, { useState, useEffect } from "react"; import { useAuth } from "../contexts/AuthContext"; import { useData } from "../contexts/DataContext"; import { UserRole } from "../types"; import { Button } from "../components/Button"; import { getCadastroFot, deleteCadastroFot, checkFotHasEvents } from "../services/apiService"; import { Briefcase, AlertTriangle, Plus, Edit, Trash2, Search, Filter } from "lucide-react"; import { FotForm } from "../components/FotForm"; interface FotData { id: string; fot: number; empresa_nome: string; curso_nome: string; observacoes: string; instituicao: string; ano_formatura_label: string; cidade: string; estado: string; gastos_captacao: number; pre_venda: boolean; empresa_id?: string; curso_id?: string; ano_formatura_id?: string; } export const CourseManagement: React.FC = () => { const { user } = useAuth(); const { events } = useData(); const [fotList, setFotList] = useState([]); const [filteredList, setFilteredList] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); // Modal State const [showForm, setShowForm] = useState(false); const [editingFot, setEditingFot] = useState(null); // Filter State const [searchTerm, setSearchTerm] = useState(""); // Verificar se è admin const isAdmin = user?.role === UserRole.SUPERADMIN || user?.role === UserRole.BUSINESS_OWNER; useEffect(() => { fetchFotData(); }, [isAdmin]); useEffect(() => { if (searchTerm.trim() === "") { setFilteredList(fotList); } else { const lowerTerm = searchTerm.toLowerCase(); const filtered = fotList.filter(item => item.fot.toString().includes(lowerTerm) || item.empresa_nome.toLowerCase().includes(lowerTerm) || item.curso_nome.toLowerCase().includes(lowerTerm) || item.instituicao.toLowerCase().includes(lowerTerm) ); setFilteredList(filtered); } }, [searchTerm, fotList]); const fetchFotData = async () => { if (!isAdmin) return; const token = localStorage.getItem("token"); if (!token) return; try { setIsLoading(true); const response = await getCadastroFot(token); if (response.data) { setFotList(response.data); setError(null); } else if (response.error) { setError(response.error); } } catch (err) { console.error(err); setError("Erro ao carregar dados."); } finally { setIsLoading(false); } }; const handleFormSubmit = () => { setShowForm(false); setEditingFot(null); fetchFotData(); // Refresh list after successful creation/update }; const handleEdit = (item: FotData) => { setEditingFot(item); setShowForm(true); }; const handleDelete = async (id: string, fotNumber: number) => { const token = localStorage.getItem("token"); if (!token) return; try { // Primeiro, verificar se há eventos associados ao FOT // Verificação local usando os eventos do DataContext const associatedEvents = events.filter(event => event.fotId === id || (typeof event.fot === 'number' && event.fot === fotNumber) ); if (associatedEvents.length > 0) { alert( `Não é possível excluir este FOT pois existem ${associatedEvents.length} evento(s) associado(s) a ele.\n\n` + `Eventos associados:\n${associatedEvents.map(e => `- ${e.name} (${new Date(e.date + "T00:00:00").toLocaleDateString("pt-BR")})`).join('\n')}` ); return; } // Tentar verificação adicional via API se disponível try { const checkResult = await checkFotHasEvents(id, token); if (checkResult.data?.hasEvents) { alert( `Não é possível excluir este FOT pois existem ${checkResult.data.eventCount} evento(s) associado(s) a ele no sistema.` ); return; } } catch (apiError) { // Se a API não estiver disponível, continua com a verificação local console.log("API check not available, using local verification"); } // Se chegou até aqui, não há eventos associados if (!window.confirm(`Tem certeza que deseja excluir o FOT ${fotNumber}?`)) return; const res = await deleteCadastroFot(id, token); if (res.error) { alert(res.error); } else { fetchFotData(); } } catch (err) { console.error(err); alert("Erro ao excluir."); } }; // Extract existing FOT numbers for uniqueness validation const existingFots = fotList.map(item => item.fot); if (!isAdmin) { return (

Acesso Negado

Apenas administradores podem acessar esta página.

); } return (
{/* Header */}

Gestão de FOT

Gerencie todas as turmas FOT cadastradas

{/* Filters Bar */}
setSearchTerm(e.target.value)} />
{/* Can add more filters here later */}
{/* Form Modal */} {showForm && (
{ setShowForm(false); setEditingFot(null); }} onSubmit={handleFormSubmit} token={localStorage.getItem("token") || ""} existingFots={existingFots} initialData={editingFot} />
)} {/* Error State */} {error && (

{error}

)} {/* Courses Table */}
{isLoading ? (
Carregando dados...
) : ( <>
{filteredList.length === 0 ? (

Nenhuma turma FOT encontrada

) : ( filteredList.map((item) => (
FOT {item.fot}
{item.empresa_nome}
{item.pre_venda ? "Pré-venda" : "Regular"}

Curso: {item.curso_nome}

Inst: {item.instituicao}

{item.cidade} - {item.estado} {item.ano_formatura_label}

{item.observacoes && (

{item.observacoes}

)}
{item.gastos_captacao ? item.gastos_captacao.toLocaleString("pt-BR", { style: "currency", currency: "BRL" }) : "R$ 0,00"}
)) )}
{filteredList.length === 0 ? ( ) : ( filteredList.map((item) => ( )) )}
FOT Empresa Curso Instituição Ano Formatura Cidade Estado Observações Gastos Captação Pré Venda Ações

Nenhuma turma FOT encontrada

{item.fot || "-"}
{(() => { const hasEvents = events.some(event => event.fotId === item.id || (typeof event.fot === 'number' && event.fot === item.fot) ); return hasEvents && ( Com eventos ); })()}
{item.empresa_nome || "-"}
{item.curso_nome || "-"}
{item.instituicao || "-"}
{item.ano_formatura_label || "-"}
{item.cidade || "-"}
{item.estado || "-"}
{item.observacoes || "-"}
{item.gastos_captacao ? item.gastos_captacao.toLocaleString("pt-BR", { style: "currency", currency: "BRL", }) : "R$ 0,00"}
{item.pre_venda ? "Sim" : "Não"}
{(() => { const hasEvents = events.some(event => event.fotId === item.id || (typeof event.fot === 'number' && event.fot === item.fot) ); return ( ); })()}
)}
); };