first commit
This commit is contained in:
@@ -0,0 +1,467 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { ArrowLeft, Trash2, Pencil, X } from 'lucide-react';
|
||||
import { formatCurrency, formatDate } from '@/lib/utils/format';
|
||||
|
||||
interface Customer {
|
||||
id: number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
whatsapp: string | null;
|
||||
address: string | null;
|
||||
city: string | null;
|
||||
notes: string | null;
|
||||
customerType: string;
|
||||
isActive: boolean;
|
||||
tags: Array<{ id: number; name: string; color: string | null }>;
|
||||
}
|
||||
|
||||
interface Stats {
|
||||
orderCount: number;
|
||||
totalSpent: number;
|
||||
avgTicket: number;
|
||||
lastPurchaseDate: string | null;
|
||||
topProducts: Array<{
|
||||
variantId: number;
|
||||
totalQuantity: number;
|
||||
productName: string;
|
||||
sku: string;
|
||||
size: string;
|
||||
color: string | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface PurchaseHistory {
|
||||
id: number;
|
||||
saleNumber: string;
|
||||
saleDate: Date;
|
||||
totalAmount: number;
|
||||
status: string;
|
||||
paymentMethod: string;
|
||||
}
|
||||
|
||||
type Tab = 'info' | 'history' | 'stats';
|
||||
|
||||
interface CustomerDetailClientProps {
|
||||
customer: Customer;
|
||||
stats: Stats;
|
||||
purchaseHistory: PurchaseHistory[];
|
||||
}
|
||||
|
||||
function SaleStatusBadge({ status }: { status: string }) {
|
||||
const colors: Record<string, string> = {
|
||||
DRAFT: 'bg-gray-100 text-gray-800',
|
||||
CONFIRMED: 'bg-blue-100 text-blue-800',
|
||||
DELIVERED: 'bg-green-100 text-green-800',
|
||||
CANCELLED: 'bg-red-100 text-red-800',
|
||||
PARTIALLY_RETURNED: 'bg-yellow-100 text-yellow-800',
|
||||
RETURNED: 'bg-orange-100 text-orange-800',
|
||||
};
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full px-2 py-1 text-xs ${colors[status] || 'bg-gray-100 text-gray-800'}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function CustomerDetailClient({
|
||||
customer,
|
||||
stats,
|
||||
purchaseHistory,
|
||||
}: CustomerDetailClientProps) {
|
||||
const router = useRouter();
|
||||
const [activeTab, setActiveTab] = useState<Tab>('info');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function handleDeactivate() {
|
||||
if (!confirm('¿Estás seguro de que querés desactivar este cliente?')) return;
|
||||
fetch(`/api/customers/${customer.id}`, { method: 'DELETE' }).then(() => router.refresh());
|
||||
}
|
||||
|
||||
async function handleSave(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const body = {
|
||||
firstName: formData.get('firstName') as string,
|
||||
lastName: formData.get('lastName') as string,
|
||||
email: (formData.get('email') as string) || undefined,
|
||||
phone: (formData.get('phone') as string) || undefined,
|
||||
whatsapp: (formData.get('whatsapp') as string) || undefined,
|
||||
address: (formData.get('address') as string) || undefined,
|
||||
city: (formData.get('city') as string) || undefined,
|
||||
notes: (formData.get('notes') as string) || undefined,
|
||||
customerType: (formData.get('customerType') as string) || 'RETAIL',
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/customers/${customer.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
setError(data.error || 'Error al guardar');
|
||||
return;
|
||||
}
|
||||
|
||||
setEditing(false);
|
||||
router.refresh();
|
||||
} catch {
|
||||
setError('Error al guardar');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
const tabs: { key: Tab; label: string }[] = [
|
||||
{ key: 'info', label: 'Info' },
|
||||
{ key: 'history', label: `Historial (${purchaseHistory.length})` },
|
||||
{ key: 'stats', label: 'Estadísticas' },
|
||||
];
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
RETAIL: 'Minorista',
|
||||
WHOLESALE: 'Mayorista',
|
||||
VIP: 'VIP',
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<Link href="/admin21/customers">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<div className="flex-1">
|
||||
<h1 className="text-2xl font-bold tracking-tight">{customer.displayName}</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{typeLabels[customer.customerType] || customer.customerType}
|
||||
{customer.tags.length > 0 && ` · ${customer.tags.map((t) => t.name).join(', ')}`}
|
||||
</p>
|
||||
</div>
|
||||
{customer.isActive && !editing && (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setEditing(true)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="outline" onClick={handleDeactivate}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Desactivar
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{editing && (
|
||||
<Button variant="ghost" onClick={() => { setEditing(false); setError(null); }}>
|
||||
<X className="mr-2 h-4 w-4" />
|
||||
Cancelar
|
||||
</Button>
|
||||
)}
|
||||
{!customer.isActive && (
|
||||
<span className="inline-flex items-center rounded-full bg-red-500/10 px-3 py-1 text-sm text-red-400 border border-red-500/30">
|
||||
Inactivo
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 border-b">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => setActiveTab(tab.key)}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors ${
|
||||
activeTab === tab.key
|
||||
? 'border-b-2 border-primary text-primary'
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Tab content */}
|
||||
{activeTab === 'info' && !editing && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Información del Cliente</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<dl className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">Nombre</dt>
|
||||
<dd>{customer.firstName} {customer.lastName}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">Tipo</dt>
|
||||
<dd>{typeLabels[customer.customerType] || customer.customerType}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">Correo electrónico</dt>
|
||||
<dd>{customer.email || '—'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">Teléfono</dt>
|
||||
<dd>{customer.phone || '—'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">WhatsApp</dt>
|
||||
<dd>{customer.whatsapp || '—'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-muted-foreground">Ciudad</dt>
|
||||
<dd>{customer.city || '—'}</dd>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<dt className="text-sm font-medium text-muted-foreground">Dirección</dt>
|
||||
<dd>{customer.address || '—'}</dd>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<dt className="text-sm font-medium text-muted-foreground">Notas</dt>
|
||||
<dd>{customer.notes || '—'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{activeTab === 'info' && editing && (
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Editar Cliente</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSave} className="space-y-4">
|
||||
{error && (
|
||||
<div className="rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-400">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="firstName">Nombre *</Label>
|
||||
<Input id="firstName" name="firstName" defaultValue={customer.firstName} required />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="lastName">Apellido *</Label>
|
||||
<Input id="lastName" name="lastName" defaultValue={customer.lastName} required />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">Correo electrónico</Label>
|
||||
<Input id="email" name="email" type="email" defaultValue={customer.email ?? ''} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="phone">Teléfono</Label>
|
||||
<Input id="phone" name="phone" defaultValue={customer.phone ?? ''} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="whatsapp">WhatsApp</Label>
|
||||
<Input id="whatsapp" name="whatsapp" defaultValue={customer.whatsapp ?? ''} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="city">Ciudad</Label>
|
||||
<Input id="city" name="city" defaultValue={customer.city ?? ''} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="address">Dirección</Label>
|
||||
<Input id="address" name="address" defaultValue={customer.address ?? ''} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="customerType">Tipo de Cliente</Label>
|
||||
<Select name="customerType" defaultValue={customer.customerType}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="RETAIL">Minorista</SelectItem>
|
||||
<SelectItem value="WHOLESALE">Mayorista</SelectItem>
|
||||
<SelectItem value="VIP">VIP</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="notes">Notas</Label>
|
||||
<textarea
|
||||
id="notes"
|
||||
name="notes"
|
||||
rows={3}
|
||||
defaultValue={customer.notes ?? ''}
|
||||
className="flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button type="submit" disabled={saving}>
|
||||
{saving ? 'Guardando...' : 'Guardar'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => { setEditing(false); setError(null); }}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{activeTab === 'history' && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Historial de Compras</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Número</TableHead>
|
||||
<TableHead>Fecha</TableHead>
|
||||
<TableHead>Total</TableHead>
|
||||
<TableHead>Pago</TableHead>
|
||||
<TableHead>Estado</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{purchaseHistory.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground py-8">
|
||||
Sin compras aún
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
purchaseHistory.map((sale) => (
|
||||
<TableRow key={sale.id}>
|
||||
<TableCell className="font-medium">
|
||||
<Link href={`/admin21/sales/${sale.id}`} className="hover:underline">
|
||||
{sale.saleNumber}
|
||||
</Link>
|
||||
</TableCell>
|
||||
<TableCell>{formatDate(sale.saleDate)}</TableCell>
|
||||
<TableCell>{formatCurrency(sale.totalAmount)}</TableCell>
|
||||
<TableCell className="capitalize">{sale.paymentMethod}</TableCell>
|
||||
<TableCell>
|
||||
<SaleStatusBadge status={sale.status} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{activeTab === 'stats' && (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Pedidos</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{stats.orderCount}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Total Gastado</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{formatCurrency(stats.totalSpent)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Ticket Promedio</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">{formatCurrency(stats.avgTicket)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Última Compra</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-2xl font-bold">
|
||||
{stats.lastPurchaseDate ? formatDate(stats.lastPurchaseDate) : '—'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{stats.topProducts.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Productos Más Comprados</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Producto</TableHead>
|
||||
<TableHead>SKU</TableHead>
|
||||
<TableHead>Variante</TableHead>
|
||||
<TableHead className="text-right">Unidades</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{stats.topProducts.map((p) => (
|
||||
<TableRow key={p.variantId}>
|
||||
<TableCell className="font-medium">{p.productName}</TableCell>
|
||||
<TableCell className="text-muted-foreground">{p.sku}</TableCell>
|
||||
<TableCell>{p.size}{p.color ? ` / ${p.color}` : ''}</TableCell>
|
||||
<TableCell className="text-right">{p.totalQuantity}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { notFound } from 'next/navigation';
|
||||
import { getCustomerById, getCustomerStats } from '@/lib/customers';
|
||||
import { db } from '@/lib/db';
|
||||
import { sales, customers } from '@/lib/db/schema';
|
||||
import { eq, desc, and, sql } from 'drizzle-orm';
|
||||
import { CustomerDetailClient } from './customer-detail-client';
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
export default async function CustomerDetailPage({ params }: RouteContext) {
|
||||
const { id } = await params;
|
||||
const customerId = parseInt(id);
|
||||
if (isNaN(customerId)) notFound();
|
||||
|
||||
let customer;
|
||||
let stats;
|
||||
try {
|
||||
[customer, stats] = await Promise.all([
|
||||
getCustomerById(customerId),
|
||||
getCustomerStats(customerId),
|
||||
]);
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Get purchase history
|
||||
const purchaseHistory = await db
|
||||
.select({
|
||||
id: sales.id,
|
||||
saleNumber: sales.saleNumber,
|
||||
saleDate: sales.saleDate,
|
||||
totalAmount: sales.totalAmount,
|
||||
status: sales.status,
|
||||
paymentMethod: sales.paymentMethod,
|
||||
})
|
||||
.from(sales)
|
||||
.where(eq(sales.customerId, customerId))
|
||||
.orderBy(desc(sales.saleDate))
|
||||
.limit(50);
|
||||
|
||||
return (
|
||||
<CustomerDetailClient
|
||||
customer={customer}
|
||||
stats={stats}
|
||||
purchaseHistory={purchaseHistory}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user