'use client'; import React, { useState, useEffect, Fragment } from 'react'; import { PlusIcon, MagnifyingGlassIcon, UserIcon, BriefcaseIcon, TrashIcon, PencilSquareIcon, ArrowRightIcon, XMarkIcon, } from '@heroicons/react/24/outline'; import { erpApi, Entity } from '@/lib/api-erp'; import { useToast } from '@/components/layout/ToastContext'; import { StatsCard, DataTable, Input, Card, CustomSelect, PageHeader, BulkActionBar, ConfirmDialog, } from "@/components/ui"; import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from '@headlessui/react'; import { SolutionGuard } from '@/components/auth/SolutionGuard'; import Link from 'next/link'; interface CRMCustomer { id: string; name: string; email: string; company: string; phone: string; } function EntidadesContent() { const toast = useToast(); const [entities, setEntities] = useState([]); const [crmCustomers, setCrmCustomers] = useState([]); const [loading, setLoading] = useState(true); const [searchTerm, setSearchTerm] = useState(''); const [isModalOpen, setIsModalOpen] = useState(false); const [confirmOpen, setConfirmOpen] = useState(false); const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false); const [entityToDelete, setEntityToDelete] = useState(null); const [editingEntity, setEditingEntity] = useState | null>(null); const [selectedIds, setSelectedIds] = useState<(string | number)[]>([]); const [formData, setFormData] = useState>({ name: '', type: 'supplier', document: '', email: '', phone: '', address: '', }); useEffect(() => { fetchAllData(); }, []); const fetchAllData = async (silent = false) => { try { if (!silent) setLoading(true); const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null; const [erpData, crmResp] = await Promise.all([ erpApi.getEntities(), fetch('/api/crm/customers', { headers: { 'Authorization': `Bearer ${token}` } }).then(res => res.ok ? res.json() : []) ]); setEntities(erpData || []); setCrmCustomers(crmResp?.customers || crmResp || []); } catch (error) { toast.error('Erro ao carregar', 'Não foi possível carregar os dados financeiros'); } finally { setLoading(false); setSelectedIds([]); } }; const handleSave = async (e: React.FormEvent) => { e.preventDefault(); try { if (editingEntity?.id) { await erpApi.updateEntity(editingEntity.id, formData); toast.success('Cadastro atualizado!'); } else { await erpApi.createEntity(formData); toast.success('Entidade cadastrada!'); } setIsModalOpen(false); setEditingEntity(null); await fetchAllData(); } catch (error) { toast.error('Erro ao salvar'); } }; const handleConfirmDelete = async () => { if (!entityToDelete) return; const originalEntities = [...entities]; const idToDelete = String(entityToDelete); // Dynamic: remove instantly setEntities(prev => prev.filter(e => String(e.id) !== idToDelete)); try { await erpApi.deleteEntity(idToDelete); toast.success('Exclusão completa', 'A entidade foi removida com sucesso.'); setTimeout(() => fetchAllData(true), 500); } catch (error) { setEntities(originalEntities); toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir a entidade.'); } finally { setConfirmOpen(false); setEntityToDelete(null); } }; const handleBulkDelete = async () => { if (selectedIds.length === 0) return; setBulkConfirmOpen(true); }; const handleConfirmBulkDelete = async () => { const erpIds = selectedIds.filter(id => { const item = combinedData.find(d => d.id === id); return item?.source === 'ERP'; }).map(String); if (erpIds.length === 0) return; const originalEntities = [...entities]; // Dynamic: remove instantly setEntities(prev => prev.filter(e => !erpIds.includes(String(e.id)))); try { await Promise.all(erpIds.map(id => erpApi.deleteEntity(id))); toast.success('Exclusão completa', `${erpIds.length} entidades excluídas com sucesso.`); setTimeout(() => fetchAllData(true), 500); } catch (error) { setEntities(originalEntities); toast.error('Erro ao excluir', 'Ocorreu um erro ao excluir algumas entidades.'); } finally { setBulkConfirmOpen(false); setSelectedIds([]); } }; // Combine both for searching const combinedData = [ ...crmCustomers.map(c => ({ id: c.id, name: c.name, email: c.email, phone: c.phone, source: 'CRM' as const, type: 'Cliente (CRM)', original: c })), ...entities.map(e => ({ id: e.id, name: e.name, email: e.email, phone: e.phone, source: 'ERP' as const, type: e.type === 'customer' ? 'Cliente (ERP)' : (e.type === 'supplier' ? 'Fornecedor (ERP)' : 'Ambos'), original: e })) ]; const filteredData = combinedData.filter(d => d.name.toLowerCase().includes(searchTerm.toLowerCase()) || (d.email || '').toLowerCase().includes(searchTerm.toLowerCase()) ); if (loading && combinedData.length === 0) return (
Carregando parceiros de negócio...
); return (
, onClick: () => { setEditingEntity(null); setFormData({ name: '', type: 'supplier', document: '', email: '', phone: '', address: '' }); setIsModalOpen(true); } }} secondaryAction={{ label: "Ir para CRM Clientes", icon: , onClick: () => window.location.href = '/crm/clientes' }} />
} /> e.type === 'supplier' || e.type === 'both').length} icon={} />
setSearchTerm(e.target.value)} leftIcon={} />
(
{row.name}
{row.source} {row.type}
) }, { header: 'E-mail', accessor: (row) => row.email || '-' }, { header: 'Telefone', accessor: (row) => row.phone || '-' }, { header: '', className: 'text-right', accessor: (row) => (
{row.source === 'ERP' ? ( <> ) : ( e.stopPropagation()} className="p-2 text-zinc-400 hover:text-brand-500 flex items-center gap-1 text-xs font-bold"> Ver no CRM )}
) } ]} />
{/* Modal de Cadastro ERP (Fornecedores) */} setIsModalOpen(false)}>
{editingEntity ? 'Editar Fornecedor' : 'Novo Fornecedor / Outros'}
setFormData({ ...formData, name: e.target.value })} required /> setFormData({ ...formData, type: val as any })} />
setFormData({ ...formData, document: e.target.value })} /> setFormData({ ...formData, phone: e.target.value })} />
setFormData({ ...formData, email: e.target.value })} /> setFormData({ ...formData, address: e.target.value })} />
setConfirmOpen(false)} onConfirm={handleConfirmDelete} title="Excluir Cadastro" message="Tem certeza? Isso pode afetar lançamentos vinculados a esta entidade no ERP." confirmText="Excluir" /> setBulkConfirmOpen(false)} onConfirm={handleConfirmBulkDelete} title="Excluir Itens Selecionados" message={`Tem certeza que deseja excluir as entidades selecionadas? Esta ação não pode ser desfeita.`} confirmText="Excluir Tudo" variant="danger" /> setSelectedIds([])} actions={[ { label: "Excluir Selecionados", icon: , onClick: handleBulkDelete, variant: 'danger' } ]} />
); } export default function EntidadesPage() { return ( ); }