- Add bulk XML CFDI upload support (up to 300MB) - Add period selector component for month/year navigation - Fix session persistence on page refresh (Zustand hydration) - Fix income/expense classification based on tenant RFC - Fix IVA calculation from XML (correct Impuestos element) - Add error handling to reportes page - Support multiple CORS origins - Update reportes service with proper Decimal/BigInt handling - Add RFC to tenant view store for proper CFDI classification - Update README with changelog and new features Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
339 lines
13 KiB
TypeScript
339 lines
13 KiB
TypeScript
'use client';
|
|
|
|
import { useState } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import { Header } from '@/components/layouts/header';
|
|
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Input } from '@/components/ui/input';
|
|
import { Label } from '@/components/ui/label';
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
|
import { useTenants, useCreateTenant, useUpdateTenant, useDeleteTenant } from '@/lib/hooks/use-tenants';
|
|
import { useTenantViewStore } from '@/stores/tenant-view-store';
|
|
import { useAuthStore } from '@/stores/auth-store';
|
|
import { Building, Plus, Users, Eye, Calendar, Pencil, Trash2, X } from 'lucide-react';
|
|
import type { Tenant } from '@/lib/api/tenants';
|
|
|
|
type PlanType = 'starter' | 'business' | 'professional' | 'enterprise';
|
|
|
|
export default function ClientesPage() {
|
|
const { user } = useAuthStore();
|
|
const { data: tenants, isLoading } = useTenants();
|
|
const createTenant = useCreateTenant();
|
|
const updateTenant = useUpdateTenant();
|
|
const deleteTenant = useDeleteTenant();
|
|
const { setViewingTenant } = useTenantViewStore();
|
|
const router = useRouter();
|
|
const queryClient = useQueryClient();
|
|
|
|
const [showForm, setShowForm] = useState(false);
|
|
const [editingTenant, setEditingTenant] = useState<Tenant | null>(null);
|
|
const [formData, setFormData] = useState<{
|
|
nombre: string;
|
|
rfc: string;
|
|
plan: PlanType;
|
|
}>({
|
|
nombre: '',
|
|
rfc: '',
|
|
plan: 'starter',
|
|
});
|
|
|
|
// Only admins can access this page
|
|
if (user?.role !== 'admin') {
|
|
return (
|
|
<>
|
|
<Header title="Clientes" />
|
|
<main className="p-6">
|
|
<Card>
|
|
<CardContent className="py-12 text-center">
|
|
<p className="text-muted-foreground">
|
|
No tienes permisos para ver esta página.
|
|
</p>
|
|
</CardContent>
|
|
</Card>
|
|
</main>
|
|
</>
|
|
);
|
|
}
|
|
|
|
const handleSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
try {
|
|
if (editingTenant) {
|
|
await updateTenant.mutateAsync({ id: editingTenant.id, data: formData });
|
|
setEditingTenant(null);
|
|
} else {
|
|
await createTenant.mutateAsync(formData);
|
|
}
|
|
setFormData({ nombre: '', rfc: '', plan: 'starter' });
|
|
setShowForm(false);
|
|
} catch (error) {
|
|
console.error('Error:', error);
|
|
}
|
|
};
|
|
|
|
const handleEdit = (tenant: Tenant) => {
|
|
setEditingTenant(tenant);
|
|
setFormData({
|
|
nombre: tenant.nombre,
|
|
rfc: tenant.rfc,
|
|
plan: tenant.plan as PlanType,
|
|
});
|
|
setShowForm(true);
|
|
};
|
|
|
|
const handleDelete = async (tenant: Tenant) => {
|
|
if (confirm(`¿Eliminar el cliente "${tenant.nombre}"? Esta acción desactivará el cliente.`)) {
|
|
try {
|
|
await deleteTenant.mutateAsync(tenant.id);
|
|
} catch (error) {
|
|
console.error('Error deleting tenant:', error);
|
|
}
|
|
}
|
|
};
|
|
|
|
const handleCancelForm = () => {
|
|
setShowForm(false);
|
|
setEditingTenant(null);
|
|
setFormData({ nombre: '', rfc: '', plan: 'starter' });
|
|
};
|
|
|
|
const handleViewClient = (tenantId: string, tenantName: string) => {
|
|
setViewingTenant(tenantId, tenantName);
|
|
queryClient.invalidateQueries();
|
|
router.push('/dashboard');
|
|
};
|
|
|
|
const formatDate = (dateString: string) => {
|
|
return new Date(dateString).toLocaleDateString('es-MX', {
|
|
year: 'numeric',
|
|
month: 'short',
|
|
day: 'numeric',
|
|
});
|
|
};
|
|
|
|
const planLabels: Record<string, string> = {
|
|
starter: 'Starter',
|
|
business: 'Business',
|
|
professional: 'Professional',
|
|
enterprise: 'Enterprise',
|
|
};
|
|
|
|
const planColors: Record<string, string> = {
|
|
starter: 'bg-muted text-muted-foreground',
|
|
business: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100',
|
|
professional: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100',
|
|
enterprise: 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-100',
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<Header title="Gestión de Clientes" />
|
|
<main className="p-6 space-y-6">
|
|
{/* Stats */}
|
|
<div className="grid gap-4 md:grid-cols-3">
|
|
<Card>
|
|
<CardContent className="pt-6">
|
|
<div className="flex items-center gap-4">
|
|
<div className="p-3 bg-primary/10 rounded-lg">
|
|
<Building className="h-6 w-6 text-primary" />
|
|
</div>
|
|
<div>
|
|
<p className="text-2xl font-bold">{tenants?.length || 0}</p>
|
|
<p className="text-sm text-muted-foreground">Total Clientes</p>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
<Card>
|
|
<CardContent className="pt-6">
|
|
<div className="flex items-center gap-4">
|
|
<div className="p-3 bg-success/10 rounded-lg">
|
|
<Users className="h-6 w-6 text-success" />
|
|
</div>
|
|
<div>
|
|
<p className="text-2xl font-bold">
|
|
{tenants?.reduce((acc, t) => acc + (t._count?.users || 0), 0) || 0}
|
|
</p>
|
|
<p className="text-sm text-muted-foreground">Total Usuarios</p>
|
|
</div>
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
<Card>
|
|
<CardContent className="pt-6">
|
|
<Button onClick={() => setShowForm(true)} className="w-full h-full min-h-[60px]">
|
|
<Plus className="h-5 w-5 mr-2" />
|
|
Agregar Cliente
|
|
</Button>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
{/* Add/Edit Client Form */}
|
|
{showForm && (
|
|
<Card>
|
|
<CardHeader>
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<CardTitle className="text-base">
|
|
{editingTenant ? 'Editar Cliente' : 'Nuevo Cliente'}
|
|
</CardTitle>
|
|
<CardDescription>
|
|
{editingTenant
|
|
? 'Modifica los datos del cliente'
|
|
: 'Registra un nuevo cliente para gestionar su facturación'}
|
|
</CardDescription>
|
|
</div>
|
|
<Button variant="ghost" size="icon" onClick={handleCancelForm}>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={handleSubmit} className="space-y-4">
|
|
<div className="grid gap-4 md:grid-cols-2">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="nombre">Nombre de la Empresa</Label>
|
|
<Input
|
|
id="nombre"
|
|
value={formData.nombre}
|
|
onChange={(e) => setFormData({ ...formData, nombre: e.target.value })}
|
|
placeholder="Empresa SA de CV"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="rfc">RFC</Label>
|
|
<Input
|
|
id="rfc"
|
|
value={formData.rfc}
|
|
onChange={(e) => setFormData({ ...formData, rfc: e.target.value.toUpperCase() })}
|
|
placeholder="XAXX010101000"
|
|
maxLength={13}
|
|
required
|
|
disabled={!!editingTenant} // Can't change RFC after creation
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="plan">Plan</Label>
|
|
<Select
|
|
value={formData.plan}
|
|
onValueChange={(value) =>
|
|
setFormData({ ...formData, plan: value as PlanType })
|
|
}
|
|
>
|
|
<SelectTrigger>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="starter">Starter - 500 CFDIs, 3 usuarios</SelectItem>
|
|
<SelectItem value="business">Business - 1,000 CFDIs, 5 usuarios</SelectItem>
|
|
<SelectItem value="professional">Professional - 2,000 CFDIs, 10 usuarios</SelectItem>
|
|
<SelectItem value="enterprise">Enterprise - Ilimitado</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="flex gap-2 justify-end">
|
|
<Button type="button" variant="outline" onClick={handleCancelForm}>
|
|
Cancelar
|
|
</Button>
|
|
<Button type="submit" disabled={createTenant.isPending || updateTenant.isPending}>
|
|
{editingTenant
|
|
? (updateTenant.isPending ? 'Guardando...' : 'Guardar Cambios')
|
|
: (createTenant.isPending ? 'Creando...' : 'Crear Cliente')}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{/* Clients List */}
|
|
<Card>
|
|
<CardHeader>
|
|
<CardTitle className="text-base">Lista de Clientes</CardTitle>
|
|
</CardHeader>
|
|
<CardContent>
|
|
{isLoading ? (
|
|
<div className="text-center py-8 text-muted-foreground">Cargando...</div>
|
|
) : tenants && tenants.length > 0 ? (
|
|
<div className="space-y-3">
|
|
{tenants.map((tenant) => (
|
|
<div
|
|
key={tenant.id}
|
|
className="flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors"
|
|
>
|
|
<div className="flex items-center gap-4">
|
|
<div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center">
|
|
<span className="font-bold text-primary">
|
|
{tenant.nombre.substring(0, 2).toUpperCase()}
|
|
</span>
|
|
</div>
|
|
<div>
|
|
<p className="font-medium">{tenant.nombre}</p>
|
|
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
|
<span>{tenant.rfc}</span>
|
|
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${planColors[tenant.plan]}`}>
|
|
{planLabels[tenant.plan]}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center gap-4">
|
|
<div className="text-right">
|
|
<div className="flex items-center gap-1 text-sm">
|
|
<Users className="h-4 w-4 text-muted-foreground" />
|
|
<span>{tenant._count?.users || 0} usuarios</span>
|
|
</div>
|
|
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
|
<Calendar className="h-3 w-3" />
|
|
<span>{formatDate(tenant.createdAt)}</span>
|
|
</div>
|
|
</div>
|
|
<div className="flex gap-1">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => handleViewClient(tenant.id, tenant.nombre)}
|
|
>
|
|
<Eye className="h-4 w-4 mr-1" />
|
|
Ver
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => handleEdit(tenant)}
|
|
title="Editar"
|
|
>
|
|
<Pencil className="h-4 w-4" />
|
|
</Button>
|
|
<Button
|
|
variant="ghost"
|
|
size="icon"
|
|
onClick={() => handleDelete(tenant)}
|
|
title="Eliminar"
|
|
className="text-destructive hover:text-destructive"
|
|
>
|
|
<Trash2 className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<div className="text-center py-8 text-muted-foreground">
|
|
No hay clientes registrados
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
</main>
|
|
</>
|
|
);
|
|
}
|