Files
byrachel/src/app/admin21/customers/new/page.tsx
T
2026-07-24 11:34:00 -03:00

204 lines
7.0 KiB
TypeScript

'use client';
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
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';
interface Tag {
id: number;
name: string;
color: string | null;
}
export default function NewCustomerPage() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [tags, setTags] = useState<Tag[]>([]);
const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
useEffect(() => {
fetch('/api/customer-tags')
.then((res) => res.json())
.then((data) => setTags(data.items || []))
.catch(() => {});
}, []);
function toggleTag(tagId: number) {
setSelectedTagIds((prev) =>
prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId],
);
}
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(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',
tagIds: selectedTagIds.length > 0 ? selectedTagIds : undefined,
};
try {
const res = await fetch('/api/customers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const data = await res.json();
setError(data.error || 'Error al crear cliente');
return;
}
const customer = await res.json();
router.push(`/admin21/customers/${customer.id}`);
} catch {
setError('Error al crear cliente');
} finally {
setLoading(false);
}
}
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Nuevo Cliente</h1>
<p className="text-muted-foreground">Agregá un nuevo cliente</p>
</div>
<Card className="max-w-2xl">
<CardHeader>
<CardTitle>Información del Cliente</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} 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" required />
</div>
<div className="space-y-2">
<Label htmlFor="lastName">Apellido *</Label>
<Input id="lastName" name="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" />
</div>
<div className="space-y-2">
<Label htmlFor="phone">Teléfono</Label>
<Input id="phone" name="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" />
</div>
<div className="space-y-2">
<Label htmlFor="city">Ciudad</Label>
<Input id="city" name="city" />
</div>
</div>
<div className="space-y-2">
<Label htmlFor="address">Dirección</Label>
<Input id="address" name="address" />
</div>
<div className="space-y-2">
<Label htmlFor="customerType">Tipo de Cliente</Label>
<Select name="customerType" defaultValue="RETAIL">
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="RETAIL">Minorista</SelectItem>
<SelectItem value="WHOLESALE">Mayorista</SelectItem>
<SelectItem value="VIP">VIP</SelectItem>
</SelectContent>
</Select>
</div>
{tags.length > 0 && (
<div className="space-y-2">
<Label>Etiquetas</Label>
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<button
key={tag.id}
type="button"
onClick={() => toggleTag(tag.id)}
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
selectedTagIds.includes(tag.id)
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground hover:bg-muted/80'
}`}
style={
selectedTagIds.includes(tag.id) && tag.color
? { backgroundColor: tag.color }
: undefined
}
>
{tag.name}
</button>
))}
</div>
</div>
)}
<div className="space-y-2">
<Label htmlFor="notes">Notas</Label>
<textarea
id="notes"
name="notes"
rows={3}
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={loading}>
{loading ? 'Creando...' : 'Crear Cliente'}
</Button>
<Button type="button" variant="outline" onClick={() => router.push('/admin21/customers')}>
Cancelar
</Button>
</div>
</form>
</CardContent>
</Card>
</div>
);
}