feat: redesign superadmin agencies list, implement flat design, add date filters, and fix UI bugs

This commit is contained in:
Erik Silva
2025-12-11 23:39:54 -03:00
parent 053e180321
commit dc98d5dccc
129 changed files with 20730 additions and 1611 deletions

View File

@@ -0,0 +1,342 @@
'use client';
import { BuildingOfficeIcon, ArrowLeftIcon, PaintBrushIcon, MapPinIcon } from '@heroicons/react/24/outline';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
interface AgencyTenant {
id: string;
name: string;
subdomain: string;
domain: string;
email: string;
phone: string;
website: string;
cnpj: string;
razao_social: string;
description: string;
industry: string;
team_size: string;
address: string;
neighborhood: string;
number: string;
complement: string;
city: string;
state: string;
zip: string;
primary_color: string;
secondary_color: string;
logo_url: string;
logo_horizontal_url: string;
is_active: boolean;
created_at: string;
updated_at: string;
}
interface AgencyDetails {
tenant: AgencyTenant;
admin?: {
id: string;
email: string;
name: string;
};
access_url: string;
}
export default function AgencyDetailPage() {
const params = useParams();
const [details, setDetails] = useState<AgencyDetails | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (params.id) {
fetchAgency(params.id as string);
}
}, [params.id]);
const fetchAgency = async (id: string) => {
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
// Handle both flat (legacy) and nested (new) responses
if (data.tenant) {
setDetails(data);
} else {
// Fallback for legacy flat response
setDetails({
tenant: data,
access_url: `http://${data.subdomain}.localhost`, // Fallback URL
});
}
}
} catch (error) {
console.error('Error fetching agency:', error);
} finally {
setLoading(false);
}
};
if (loading) {
return (
<div className="p-8 flex items-center justify-center min-h-[400px]">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
</div>
);
}
if (!details || !details.tenant) {
return (
<div className="p-8">
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative" role="alert">
<strong className="font-bold">Erro!</strong>
<span className="block sm:inline"> Agência não encontrada.</span>
</div>
<Link
href="/superadmin/agencies"
className="mt-4 inline-flex items-center gap-2 text-gray-600 hover:text-gray-900"
>
<ArrowLeftIcon className="w-4 h-4" />
Voltar para Agências
</Link>
</div>
);
}
const { tenant } = details;
return (
<div className="p-8 max-w-7xl mx-auto">
<div className="mb-8">
<Link
href="/superadmin/agencies"
className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200 mb-6 transition-colors"
>
<ArrowLeftIcon className="w-4 h-4" />
Voltar para Agências
</Link>
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 flex items-center justify-center p-2">
{tenant.logo_url ? (
<img src={tenant.logo_url} alt={tenant.name} className="max-h-full max-w-full object-contain" />
) : (
<BuildingOfficeIcon className="w-8 h-8 text-gray-400" />
)}
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">{tenant.name}</h1>
<div className="flex items-center gap-2 mt-1">
<a
href={details.access_url}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1"
>
{tenant.subdomain}.aggios.app
<ArrowLeftIcon className="w-3 h-3 rotate-135" />
</a>
<span className="text-gray-300 dark:text-gray-600">|</span>
<span className={`px-2 py-0.5 inline-flex text-xs font-medium rounded-full ${tenant.is_active
? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400'
}`}>
{tenant.is_active ? 'Ativa' : 'Inativa'}
</span>
</div>
</div>
</div>
<div className="flex gap-3">
<Link
href={`/superadmin/agencies/${tenant.id}/edit`}
className="px-4 py-2 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-medium text-sm"
>
Editar Dados
</Link>
<button
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium text-sm"
>
Acessar Painel
</button>
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Coluna Esquerda (2/3) */}
<div className="lg:col-span-2 space-y-6">
{/* Informações Básicas */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<BuildingOfficeIcon className="w-5 h-5 text-gray-500" />
Dados da Empresa
</h2>
</div>
<div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Razão Social</dt>
<dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">{tenant.razao_social || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">CNPJ</dt>
<dd className="mt-1 text-sm font-medium text-gray-900 dark:text-white">{tenant.cnpj || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Setor</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.industry || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Tamanho da Equipe</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.team_size || '-'}</dd>
</div>
<div className="md:col-span-2">
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Descrição</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.description || '-'}</dd>
</div>
</div>
</div>
{/* Endereço */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<MapPinIcon className="w-5 h-5 text-gray-500" />
Localização
</h2>
</div>
<div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="md:col-span-2">
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Endereço</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">
{tenant.address ? (
<>
{tenant.address}
{tenant.number ? `, ${tenant.number}` : ''}
{tenant.complement ? ` - ${tenant.complement}` : ''}
</>
) : '-'}
</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Bairro</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.neighborhood || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Cidade / UF</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">
{tenant.city && tenant.state ? `${tenant.city} - ${tenant.state}` : '-'}
</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">CEP</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.zip || '-'}</dd>
</div>
</div>
</div>
</div>
{/* Coluna Direita (1/3) */}
<div className="space-y-6">
{/* Branding */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white flex items-center gap-2">
<PaintBrushIcon className="w-5 h-5 text-gray-500" />
Identidade Visual
</h2>
</div>
<div className="p-6 space-y-6">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Cores da Marca</dt>
<div className="flex gap-4">
<div className="text-center">
<div
className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
style={{ backgroundColor: tenant.primary_color || '#000000' }}
/>
<span className="text-xs font-mono text-gray-500">{tenant.primary_color || '-'}</span>
</div>
<div className="text-center">
<div
className="w-12 h-12 rounded-lg border border-gray-200 dark:border-gray-700 mb-1"
style={{ backgroundColor: tenant.secondary_color || '#ffffff' }}
/>
<span className="text-xs font-mono text-gray-500">{tenant.secondary_color || '-'}</span>
</div>
</div>
</div>
{tenant.logo_horizontal_url && (
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Logo Horizontal</dt>
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg border border-gray-200 dark:border-gray-700 flex justify-center">
<img src={tenant.logo_horizontal_url} alt="Logo Horizontal" className="max-h-12 max-w-full object-contain" />
</div>
</div>
)}
</div>
</div>
{/* Contato */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50">
<h2 className="text-base font-semibold text-gray-900 dark:text-white">
Contato
</h2>
</div>
<div className="p-6 space-y-4">
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Email</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white break-all">{tenant.email || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Telefone</dt>
<dd className="mt-1 text-sm text-gray-900 dark:text-white">{tenant.phone || '-'}</dd>
</div>
<div>
<dt className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Website</dt>
<dd className="mt-1">
{tenant.website ? (
<a
href={tenant.website}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-600 dark:text-blue-400 hover:underline break-all"
>
{tenant.website}
</a>
) : '-'}
</dd>
</div>
</div>
</div>
{/* Metadados */}
<div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-6">
<dl className="space-y-3">
<div className="flex justify-between">
<dt className="text-sm text-gray-500 dark:text-gray-400">Criada em</dt>
<dd className="text-sm font-medium text-gray-900 dark:text-white">
{new Date(tenant.created_at).toLocaleDateString('pt-BR')}
</dd>
</div>
<div className="flex justify-between">
<dt className="text-sm text-gray-500 dark:text-gray-400">Última atualização</dt>
<dd className="text-sm font-medium text-gray-900 dark:text-white">
{new Date(tenant.updated_at).toLocaleDateString('pt-BR')}
</dd>
</div>
</dl>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,364 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export default function NewAgencyPage() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState({
// Agência
agencyName: '',
subdomain: '',
cnpj: '',
razaoSocial: '',
description: '',
website: '',
industry: '',
phone: '',
teamSize: '',
// Endereço
cep: '',
state: '',
city: '',
neighborhood: '',
street: '',
number: '',
complement: '',
// Admin
adminEmail: '',
adminPassword: '',
adminName: '',
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
const response = await fetch('/api/admin/agencies/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
body: JSON.stringify(formData),
});
if (!response.ok) {
const errorData = await response.text();
throw new Error(errorData || 'Erro ao criar agência');
}
router.push('/superadmin/agencies');
} catch (err: any) {
setError(err.message);
} finally {
setLoading(false);
}
};
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
setFormData(prev => ({
...prev,
[e.target.name]: e.target.value
}));
};
return (
<div className="p-8 h-full overflow-auto">
<div className="max-w-4xl mx-auto">
<div className="mb-8">
<h1 className="text-2xl font-bold text-gray-900">Nova Agência</h1>
<p className="text-gray-600 mt-2">Cadastre uma nova agência no sistema Aggios</p>
</div>
{error && (
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-8">
{/* Informações da Agência */}
<section className="bg-white p-6 rounded-lg border border-gray-200">
<h2 className="text-lg font-semibold mb-4 text-gray-900">Informações da Agência</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nome da Agência *
</label>
<input
type="text"
name="agencyName"
required
value={formData.agencyName}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Subdomínio *
</label>
<input
type="text"
name="subdomain"
required
value={formData.subdomain}
onChange={handleChange}
placeholder="exemplo"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
<p className="text-xs text-gray-500 mt-1">Será usado como: exemplo.aggios.app</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">CNPJ</label>
<input
type="text"
name="cnpj"
value={formData.cnpj}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Razão Social</label>
<input
type="text"
name="razaoSocial"
value={formData.razaoSocial}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Website</label>
<input
type="url"
name="website"
value={formData.website}
onChange={handleChange}
placeholder="https://"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Telefone</label>
<input
type="tel"
name="phone"
value={formData.phone}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Setor</label>
<input
type="text"
name="industry"
value={formData.industry}
onChange={handleChange}
placeholder="Ex: Tecnologia, Marketing"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Tamanho do Time</label>
<select
name="teamSize"
value={formData.teamSize}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
>
<option value="">Selecione</option>
<option value="1-10">1-10 pessoas</option>
<option value="11-50">11-50 pessoas</option>
<option value="51-200">51-200 pessoas</option>
<option value="201+">201+ pessoas</option>
</select>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">Descrição</label>
<textarea
name="description"
value={formData.description}
onChange={handleChange}
rows={3}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
</div>
</section>
{/* Endereço */}
<section className="bg-white p-6 rounded-lg border border-gray-200">
<h2 className="text-lg font-semibold mb-4 text-gray-900">Endereço</h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">CEP</label>
<input
type="text"
name="cep"
value={formData.cep}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Estado</label>
<input
type="text"
name="state"
value={formData.state}
onChange={handleChange}
maxLength={2}
placeholder="SP"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Cidade</label>
<input
type="text"
name="city"
value={formData.city}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">Bairro</label>
<input
type="text"
name="neighborhood"
value={formData.neighborhood}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Número</label>
<input
type="text"
name="number"
value={formData.number}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">Rua</label>
<input
type="text"
name="street"
value={formData.street}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Complemento</label>
<input
type="text"
name="complement"
value={formData.complement}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
</div>
</section>
{/* Administrador */}
<section className="bg-white p-6 rounded-lg border border-gray-200">
<h2 className="text-lg font-semibold mb-4 text-gray-900">Administrador da Agência</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Nome do Admin *
</label>
<input
type="text"
name="adminName"
required
value={formData.adminName}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Email do Admin *
</label>
<input
type="email"
name="adminEmail"
required
value={formData.adminEmail}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
</div>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Senha do Admin *
</label>
<input
type="password"
name="adminPassword"
required
minLength={8}
value={formData.adminPassword}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-purple-500"
/>
<p className="text-xs text-gray-500 mt-1">Mínimo 8 caracteres</p>
</div>
</div>
</section>
{/* Botões */}
<div className="flex gap-3 justify-end">
<button
type="button"
onClick={() => router.back()}
className="px-6 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
>
Cancelar
</button>
<button
type="submit"
disabled={loading}
className="px-6 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 transition-colors disabled:opacity-50"
>
{loading ? 'Criando...' : 'Criar Agência'}
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -0,0 +1,533 @@
"use client";
import { Fragment, useEffect, useState } from 'react';
import Link from 'next/link';
import { Menu, Listbox, Transition } from '@headlessui/react';
import CreateAgencyModal from '@/components/agencies/CreateAgencyModal';
import {
BuildingOfficeIcon,
TrashIcon,
EyeIcon,
PencilIcon,
EllipsisVerticalIcon,
MagnifyingGlassIcon,
FunnelIcon,
CalendarIcon,
CheckIcon,
ChevronUpDownIcon,
PlusIcon,
XMarkIcon
} from '@heroicons/react/24/outline';
interface Agency {
id: string;
name: string;
subdomain: string;
domain: string;
email: string;
phone: string;
cnpj: string;
is_active: boolean;
created_at: string;
logo_url?: string;
}
const STATUS_OPTIONS = [
{ id: 'all', name: 'Todos os Status' },
{ id: 'active', name: 'Ativas' },
{ id: 'inactive', name: 'Inativas' },
];
const DATE_PRESETS = [
{ id: 'all', name: 'Todo o período' },
{ id: '7d', name: 'Últimos 7 dias' },
{ id: '15d', name: 'Últimos 15 dias' },
{ id: '30d', name: 'Últimos 30 dias' },
{ id: 'custom', name: 'Personalizado' },
];
export default function AgenciesPage() {
const [agencies, setAgencies] = useState<Agency[]>([]);
const [loading, setLoading] = useState(true);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
// Filtros
const [searchTerm, setSearchTerm] = useState('');
const [selectedStatus, setSelectedStatus] = useState(STATUS_OPTIONS[0]);
const [selectedDatePreset, setSelectedDatePreset] = useState(DATE_PRESETS[0]);
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
useEffect(() => {
fetchAgencies();
}, []);
const fetchAgencies = async () => {
try {
const response = await fetch('/api/admin/agencies', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
const data = await response.json();
setAgencies(data);
}
} catch (error) {
console.error('Error fetching agencies:', error);
} finally {
setLoading(false);
}
};
const handleDelete = async (id: string) => {
if (!confirm('Tem certeza que deseja excluir esta agência? Esta ação não pode ser desfeita.')) {
return;
}
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
},
});
if (response.ok) {
setAgencies(agencies.filter(a => a.id !== id));
} else {
alert('Erro ao excluir agência');
}
} catch (error) {
console.error('Error deleting agency:', error);
alert('Erro ao excluir agência');
}
};
const toggleActive = async (id: string, currentStatus: boolean) => {
try {
const response = await fetch(`/api/admin/agencies/${id}`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ is_active: !currentStatus }),
});
if (response.ok) {
setAgencies(agencies.map(a =>
a.id === id ? { ...a, is_active: !currentStatus } : a
));
}
} catch (error) {
console.error('Error toggling agency status:', error);
}
};
const clearFilters = () => {
setSearchTerm('');
setSelectedStatus(STATUS_OPTIONS[0]);
setSelectedDatePreset(DATE_PRESETS[0]);
setStartDate('');
setEndDate('');
};
// Lógica de Filtragem
const filteredAgencies = agencies.filter((agency) => {
// Texto
const searchLower = searchTerm.toLowerCase();
const matchesSearch =
(agency.name?.toLowerCase() || '').includes(searchLower) ||
(agency.email?.toLowerCase() || '').includes(searchLower) ||
(agency.subdomain?.toLowerCase() || '').includes(searchLower);
// Status
const matchesStatus =
selectedStatus.id === 'all' ? true :
selectedStatus.id === 'active' ? agency.is_active :
!agency.is_active;
// Data
let matchesDate = true;
const agencyDate = new Date(agency.created_at);
const now = new Date();
if (selectedDatePreset.id === 'custom') {
if (startDate) {
const start = new Date(startDate);
start.setHours(0, 0, 0, 0);
if (agencyDate < start) matchesDate = false;
}
if (endDate) {
const end = new Date(endDate);
end.setHours(23, 59, 59, 999);
if (agencyDate > end) matchesDate = false;
}
} else if (selectedDatePreset.id !== 'all') {
const diffTime = Math.abs(now.getTime() - agencyDate.getTime());
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (selectedDatePreset.id === '7d') matchesDate = diffDays <= 7;
if (selectedDatePreset.id === '15d') matchesDate = diffDays <= 15;
if (selectedDatePreset.id === '30d') matchesDate = diffDays <= 30;
}
return matchesSearch && matchesStatus && matchesDate;
});
return (
<div className="p-6 max-w-[1600px] mx-auto space-y-6">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-zinc-900 dark:text-white tracking-tight">Agências</h1>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Gerencie seus parceiros e acompanhe o desempenho.
</p>
</div>
<button
onClick={() => setIsCreateModalOpen(true)}
className="inline-flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-white rounded-lg hover:opacity-90 transition-opacity"
style={{ background: 'var(--gradient)' }}
>
<PlusIcon className="w-4 h-4" />
Nova Agência
</button>
</div>
{/* Toolbar de Filtros */}
<div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
{/* Busca */}
<div className="relative w-full lg:w-96">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<MagnifyingGlassIcon className="h-5 w-5 text-zinc-400" aria-hidden="true" />
</div>
<input
type="text"
className="block w-full pl-10 pr-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg leading-5 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 focus:outline-none focus:ring-1 focus:ring-[var(--brand-color)] focus:border-[var(--brand-color)] sm:text-sm transition duration-150 ease-in-out"
placeholder="Buscar por nome, email ou subdomínio..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
{/* Filtro de Status */}
<Listbox value={selectedStatus} onChange={setSelectedStatus}>
<div className="relative w-full sm:w-[180px]">
<Listbox.Button className="relative w-full cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300">
<span className="block truncate">{selectedStatus.name}</span>
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
<ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
</span>
</Listbox.Button>
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white dark:bg-zinc-800 py-1 text-base ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm border border-zinc-200 dark:border-zinc-700">
{STATUS_OPTIONS.map((status, statusIdx) => (
<Listbox.Option
key={statusIdx}
className={({ active, selected }) =>
`relative cursor-default select-none py-2 pl-10 pr-4 ${active ? 'bg-zinc-100 dark:bg-zinc-700 text-zinc-900 dark:text-white' : 'text-zinc-900 dark:text-zinc-100'
}`
}
value={status}
>
{({ selected }) => (
<>
<span className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}>
{status.name}
</span>
{selected ? (
<span className="absolute inset-y-0 left-0 flex items-center pl-3 text-[var(--brand-color)]">
<CheckIcon className="h-4 w-4" aria-hidden="true" />
</span>
) : null}
</>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</div>
</Listbox>
{/* Filtro de Data Unificado */}
<Menu as="div" className="relative w-full sm:w-auto">
<Menu.Button className="relative w-full sm:w-[220px] cursor-pointer rounded-lg bg-white dark:bg-zinc-900 py-2 pl-3 pr-10 text-left text-sm border border-zinc-200 dark:border-zinc-700 focus:outline-none focus:border-[var(--brand-color)] focus:ring-1 focus:ring-[var(--brand-color)] text-zinc-700 dark:text-zinc-300 flex items-center gap-2">
<CalendarIcon className="w-4 h-4 text-zinc-400" />
<span className="block truncate">
{selectedDatePreset.id === 'custom'
? (startDate && endDate ? `${new Date(startDate).toLocaleDateString()} - ${new Date(endDate).toLocaleDateString()}` : 'Selecionar período')
: selectedDatePreset.name}
</span>
<span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2">
<ChevronUpDownIcon className="h-4 w-4 text-zinc-400" aria-hidden="true" />
</span>
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="absolute right-0 z-10 mt-2 w-72 origin-top-right rounded-xl bg-white dark:bg-zinc-900 ring-1 ring-black ring-opacity-5 focus:outline-none border border-zinc-200 dark:border-zinc-700 divide-y divide-zinc-100 dark:divide-zinc-800">
<div className="p-1">
{DATE_PRESETS.filter(p => p.id !== 'custom').map((preset) => (
<Menu.Item key={preset.id}>
{({ active }) => (
<button
onClick={() => {
setSelectedDatePreset(preset);
setStartDate('');
setEndDate('');
}}
className={`${active ? 'bg-zinc-100 dark:bg-zinc-800' : ''
} ${selectedDatePreset.id === preset.id ? 'text-[var(--brand-color)] font-medium' : 'text-zinc-700 dark:text-zinc-300'
} group flex w-full items-center rounded-lg px-2 py-2 text-sm`}
>
{preset.name}
{selectedDatePreset.id === preset.id && (
<CheckIcon className="ml-auto h-4 w-4" />
)}
</button>
)}
</Menu.Item>
))}
</div>
<div className="p-3 space-y-3">
<div className="text-xs font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">
Personalizado
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<label className="block text-xs text-zinc-500 mb-1">Início</label>
<input
type="date"
value={startDate}
onChange={(e) => {
setStartDate(e.target.value);
setSelectedDatePreset(DATE_PRESETS.find(p => p.id === 'custom')!);
}}
className="block w-full px-2 py-1 text-xs border border-zinc-200 dark:border-zinc-700 rounded bg-zinc-50 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:border-[var(--brand-color)]"
/>
</div>
<div>
<label className="block text-xs text-zinc-500 mb-1">Fim</label>
<input
type="date"
value={endDate}
onChange={(e) => {
setEndDate(e.target.value);
setSelectedDatePreset(DATE_PRESETS.find(p => p.id === 'custom')!);
}}
className="block w-full px-2 py-1 text-xs border border-zinc-200 dark:border-zinc-700 rounded bg-zinc-50 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 focus:outline-none focus:border-[var(--brand-color)]"
/>
</div>
</div>
</div>
</Menu.Items>
</Transition>
</Menu>
{/* Botão Limpar */}
{(searchTerm || selectedStatus.id !== 'all' || selectedDatePreset.id !== 'all') && (
<button
onClick={clearFilters}
className="inline-flex items-center justify-center px-3 py-2 border border-zinc-200 dark:border-zinc-700 text-sm font-medium rounded-lg text-zinc-700 dark:text-zinc-200 bg-white dark:bg-zinc-900 hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--brand-color)]"
title="Limpar Filtros"
>
<XMarkIcon className="h-4 w-4" />
</button>
)}
</div>
</div>
{/* Tabela */}
{loading ? (
<div className="flex items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--brand-color)]"></div>
</div>
) : filteredAgencies.length === 0 ? (
<div className="flex flex-col items-center justify-center h-64 bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 text-center p-8">
<div className="w-16 h-16 bg-zinc-50 dark:bg-zinc-800 rounded-full flex items-center justify-center mb-4">
<BuildingOfficeIcon className="w-8 h-8 text-zinc-400" />
</div>
<h3 className="text-lg font-medium text-zinc-900 dark:text-white mb-1">
Nenhuma agência encontrada
</h3>
<p className="text-zinc-500 dark:text-zinc-400 max-w-sm mx-auto">
Não encontramos resultados para os filtros selecionados. Tente limpar a busca ou alterar os filtros.
</p>
<button
onClick={clearFilters}
className="mt-4 text-sm text-[var(--brand-color)] hover:underline font-medium"
>
Limpar todos os filtros
</button>
</div>
) : (
<div className="bg-white dark:bg-zinc-900 rounded-xl border border-zinc-200 dark:border-zinc-800 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="bg-zinc-50/50 dark:bg-zinc-800/50 border-b border-zinc-200 dark:border-zinc-800">
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Agência</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Contato</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Status</th>
<th className="px-6 py-4 text-left text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Data Cadastro</th>
<th className="px-6 py-4 text-right text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
{filteredAgencies.map((agency) => (
<tr key={agency.id} className="group hover:bg-zinc-50 dark:hover:bg-zinc-800/50 transition-colors">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-4">
{agency.logo_url ? (
<img
src={agency.logo_url}
alt={agency.name}
className="w-10 h-10 rounded-lg object-cover bg-white dark:bg-zinc-800"
/>
) : (
<div
className="w-10 h-10 rounded-lg flex items-center justify-center text-white font-bold text-sm"
style={{ background: 'var(--gradient)' }}
>
{agency.name?.substring(0, 2).toUpperCase()}
</div>
)}
<div>
<div className="text-sm font-semibold text-zinc-900 dark:text-white">
{agency.name}
</div>
<a
href={`http://${agency.subdomain}.localhost`}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-zinc-500 hover:text-[var(--brand-color)] transition-colors flex items-center gap-1"
>
{agency.subdomain}.aggios.app
</a>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex flex-col gap-0.5">
<span className="text-sm text-zinc-700 dark:text-zinc-300">{agency.email}</span>
<span className="text-xs text-zinc-400">{agency.phone || 'Sem telefone'}</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<button
onClick={() => toggleActive(agency.id, agency.is_active)}
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${agency.is_active
? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-900/30'
: 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-zinc-800 dark:text-zinc-400 dark:border-zinc-700'
}`}
>
<span className={`w-1.5 h-1.5 rounded-full ${agency.is_active ? 'bg-emerald-500' : 'bg-zinc-400'}`} />
{agency.is_active ? 'Ativo' : 'Inativo'}
</button>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-zinc-500 dark:text-zinc-400">
{new Date(agency.created_at).toLocaleDateString('pt-BR', {
day: '2-digit',
month: 'short',
year: 'numeric'
})}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right">
<Menu as="div" className="relative inline-block text-left">
<Menu.Button className="p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-800 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors outline-none">
<EllipsisVerticalIcon className="w-5 h-5" />
</Menu.Button>
<Menu.Items
transition
portal
anchor="bottom end"
className="w-48 origin-top-right divide-y divide-zinc-100 dark:divide-zinc-800 rounded-xl bg-white dark:bg-zinc-900 focus:outline-none z-50 border border-zinc-200 dark:border-zinc-800 [--anchor-gap:8px] transition duration-100 ease-out data-[closed]:scale-95 data-[closed]:opacity-0"
>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<Link
href={`/superadmin/agencies/${agency.id}`}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<EyeIcon className="mr-2 h-4 w-4 text-zinc-400" />
Detalhes
</Link>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<Link
href={`/superadmin/agencies/${agency.id}/edit`}
className={`${active ? 'bg-zinc-50 dark:bg-zinc-800' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-zinc-700 dark:text-zinc-300`}
>
<PencilIcon className="mr-2 h-4 w-4 text-zinc-400" />
Editar
</Link>
)}
</Menu.Item>
</div>
<div className="px-1 py-1">
<Menu.Item>
{({ active }) => (
<button
onClick={() => handleDelete(agency.id)}
className={`${active ? 'bg-red-50 dark:bg-red-900/20' : ''
} group flex w-full items-center rounded-lg px-2 py-2 text-sm text-red-600 dark:text-red-400`}
>
<TrashIcon className="mr-2 h-4 w-4" />
Excluir
</button>
)}
</Menu.Item>
</div>
</Menu.Items>
</Menu>
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Footer da Tabela (Paginação Mockada) */}
<div className="px-6 py-4 border-t border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-800/50 flex items-center justify-between">
<p className="text-xs text-zinc-500 dark:text-zinc-400">
Mostrando <span className="font-medium">{filteredAgencies.length}</span> resultados
</p>
<div className="flex gap-2">
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Anterior
</button>
<button disabled className="px-3 py-1 text-xs font-medium text-zinc-400 bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-md cursor-not-allowed opacity-50">
Próxima
</button>
</div>
</div>
</div>
)}
<CreateAgencyModal
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onSuccess={fetchAgencies}
/>
</div>
);
}