352 lines
12 KiB
TypeScript
352 lines
12 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import {
|
|
CheckCircle2,
|
|
Send,
|
|
Mail,
|
|
MessageSquare,
|
|
Check,
|
|
XCircle,
|
|
Clock,
|
|
RotateCcw,
|
|
Loader2,
|
|
} from "lucide-react";
|
|
import { EstadoBadge } from "@/components/EstadoBadge";
|
|
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
|
|
|
interface Props {
|
|
cotizacionId: string;
|
|
numero: string;
|
|
estado: string;
|
|
esAdmin: boolean;
|
|
clienteEmail: string | null;
|
|
clienteTelefono: string | null;
|
|
}
|
|
|
|
export function CambiarEstadoButtons({
|
|
cotizacionId,
|
|
numero,
|
|
estado,
|
|
esAdmin,
|
|
clienteEmail,
|
|
clienteTelefono,
|
|
}: Props) {
|
|
const router = useRouter();
|
|
const confirm = useConfirm();
|
|
const showToast = useToast();
|
|
const [loading, setLoading] = useState(false);
|
|
const [showEnviarModal, setShowEnviarModal] = useState(false);
|
|
const [canal, setCanal] = useState<"email" | "whatsapp_chatwoot" | "manual">(
|
|
clienteTelefono ? "whatsapp_chatwoot" : clienteEmail ? "email" : "manual"
|
|
);
|
|
const [destino, setDestino] = useState(clienteTelefono || clienteEmail || "");
|
|
const [mensaje, setMensaje] = useState("");
|
|
const [fallbackEmail, setFallbackEmail] = useState(true);
|
|
|
|
const handleAprobar = async () => {
|
|
const ok = await confirm({
|
|
title: "Aprobar cotización",
|
|
message: `¿Confirmas aprobar la cotización ${numero}? Una vez aprobada podrá enviarse al cliente por correo o WhatsApp.`,
|
|
confirmText: "Aprobar cotización",
|
|
cancelText: "Cancelar",
|
|
});
|
|
if (!ok) return;
|
|
|
|
setLoading(true);
|
|
try {
|
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/aprobar`, {
|
|
method: "POST",
|
|
});
|
|
const data = await res.json().catch(() => ({}));
|
|
if (res.ok) {
|
|
showToast("Cotización aprobada correctamente", "success");
|
|
router.refresh();
|
|
} else {
|
|
showToast(data.error || "No se pudo aprobar la cotización", "error");
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleEnviar = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
setLoading(true);
|
|
try {
|
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/enviar`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
canal,
|
|
destino: destino.trim() || undefined,
|
|
mensaje: mensaje.trim() || undefined,
|
|
fallbackEmail: canal === "whatsapp_chatwoot" ? fallbackEmail : undefined,
|
|
}),
|
|
});
|
|
const data = await res.json().catch(() => ({}));
|
|
if (res.ok) {
|
|
showToast(`Cotización enviada (${data.enviadaCanal || canal})`, "success");
|
|
setShowEnviarModal(false);
|
|
router.refresh();
|
|
} else {
|
|
showToast(data.error || "Error al enviar la cotización", "error");
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleTransicion = async (
|
|
nuevoEstado: "aceptada" | "rechazada" | "vencida" | "borrador",
|
|
etiqueta: string,
|
|
danger = false
|
|
) => {
|
|
const ok = await confirm({
|
|
title: `Cambiar estado a ${etiqueta}`,
|
|
message: `¿Confirmas marcar la cotización ${numero} como "${etiqueta}"?`,
|
|
confirmText: `Marcar ${etiqueta}`,
|
|
cancelText: "Cancelar",
|
|
danger,
|
|
});
|
|
if (!ok) return;
|
|
|
|
setLoading(true);
|
|
try {
|
|
const res = await fetch(`/api/cotizaciones/${cotizacionId}/estado`, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ estado: nuevoEstado }),
|
|
});
|
|
const data = await res.json().catch(() => ({}));
|
|
if (res.ok) {
|
|
showToast(`Cotización marcada como ${etiqueta}`, "success");
|
|
router.refresh();
|
|
} else {
|
|
showToast(data.error || "Error al cambiar estado", "error");
|
|
}
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const cambiarCanal = (nuevo: "email" | "whatsapp_chatwoot" | "manual") => {
|
|
setCanal(nuevo);
|
|
if (nuevo === "email") setDestino(clienteEmail || "");
|
|
else if (nuevo === "whatsapp_chatwoot") setDestino(clienteTelefono || "");
|
|
else setDestino(clienteEmail || clienteTelefono || "");
|
|
};
|
|
|
|
return (
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<EstadoBadge estado={estado} />
|
|
|
|
{estado === "borrador" && esAdmin && (
|
|
<button
|
|
type="button"
|
|
onClick={handleAprobar}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
|
>
|
|
{loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle2 className="w-3.5 h-3.5" />}
|
|
Aprobar cotización
|
|
</button>
|
|
)}
|
|
|
|
{estado === "aprobada" && (
|
|
<>
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowEnviarModal(true)}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
|
>
|
|
<Send className="w-3.5 h-3.5" />
|
|
Enviar cotización
|
|
</button>
|
|
{esAdmin && (
|
|
<button
|
|
type="button"
|
|
onClick={() => handleTransicion("borrador", "Borrador")}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
|
>
|
|
<RotateCcw className="w-3.5 h-3.5" />
|
|
Reabrir
|
|
</button>
|
|
)}
|
|
</>
|
|
)}
|
|
|
|
{estado === "enviada" && (
|
|
<>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleTransicion("aceptada", "Aceptada")}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-green-300 text-green-700 hover:bg-green-50 text-xs font-medium disabled:opacity-50"
|
|
>
|
|
<Check className="w-3.5 h-3.5" />
|
|
Aceptada
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleTransicion("rechazada", "Rechazada", true)}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-red-300 text-red-700 hover:bg-red-50 text-xs font-medium disabled:opacity-50"
|
|
>
|
|
<XCircle className="w-3.5 h-3.5" />
|
|
Rechazada
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleTransicion("vencida", "Vencida")}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-amber-300 text-amber-800 hover:bg-amber-50 text-xs font-medium disabled:opacity-50"
|
|
>
|
|
<Clock className="w-3.5 h-3.5" />
|
|
Vencida
|
|
</button>
|
|
</>
|
|
)}
|
|
|
|
{(estado === "rechazada" || estado === "vencida") && esAdmin && (
|
|
<button
|
|
type="button"
|
|
onClick={() => handleTransicion("borrador", "Borrador")}
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
|
>
|
|
<RotateCcw className="w-3.5 h-3.5" />
|
|
Reabrir borrador
|
|
</button>
|
|
)}
|
|
|
|
{showEnviarModal && (
|
|
<div
|
|
className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4"
|
|
onClick={() => !loading && setShowEnviarModal(false)}
|
|
>
|
|
<form
|
|
onSubmit={handleEnviar}
|
|
onClick={(e) => e.stopPropagation()}
|
|
className="bg-white rounded-xl border border-border shadow-xl max-w-md w-full p-5 space-y-4"
|
|
>
|
|
<div>
|
|
<h3 className="font-semibold text-base">Enviar cotización {numero}</h3>
|
|
<p className="text-xs text-muted mt-0.5">
|
|
El PDF oficial se genera automáticamente al confirmar el envío.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-3 gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => cambiarCanal("email")}
|
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
|
canal === "email"
|
|
? "border-primary bg-primary-light/20 text-primary"
|
|
: "border-border text-muted hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
<Mail className="w-4 h-4" />
|
|
Correo
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => cambiarCanal("whatsapp_chatwoot")}
|
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
|
canal === "whatsapp_chatwoot"
|
|
? "border-primary bg-primary-light/20 text-primary"
|
|
: "border-border text-muted hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
<MessageSquare className="w-4 h-4" />
|
|
WhatsApp
|
|
</button>
|
|
{esAdmin && (
|
|
<button
|
|
type="button"
|
|
onClick={() => cambiarCanal("manual")}
|
|
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
|
canal === "manual"
|
|
? "border-primary bg-primary-light/20 text-primary"
|
|
: "border-border text-muted hover:bg-gray-50"
|
|
}`}
|
|
>
|
|
<CheckCircle2 className="w-4 h-4" />
|
|
Manual
|
|
</button>
|
|
)}
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-xs font-medium text-muted mb-1">
|
|
{canal === "email"
|
|
? "Correo destino"
|
|
: canal === "whatsapp_chatwoot"
|
|
? "Teléfono WhatsApp"
|
|
: "Destino / referencia"}
|
|
</label>
|
|
<input
|
|
type="text"
|
|
value={destino}
|
|
onChange={(e) => setDestino(e.target.value)}
|
|
required={canal !== "manual"}
|
|
placeholder={canal === "email" ? "[email protected]" : "4421234567"}
|
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
|
/>
|
|
</div>
|
|
|
|
{canal !== "manual" && (
|
|
<div>
|
|
<label className="block text-xs font-medium text-muted mb-1">
|
|
Mensaje adicional (opcional)
|
|
</label>
|
|
<textarea
|
|
rows={3}
|
|
value={mensaje}
|
|
onChange={(e) => setMensaje(e.target.value)}
|
|
placeholder="Nota breve para acompañar la propuesta..."
|
|
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{canal === "whatsapp_chatwoot" && clienteEmail && (
|
|
<label className="flex items-center gap-2 text-xs text-muted">
|
|
<input
|
|
type="checkbox"
|
|
checked={fallbackEmail}
|
|
onChange={(e) => setFallbackEmail(e.target.checked)}
|
|
/>
|
|
Si WhatsApp está fuera de la ventana de 24h, enviar por correo ({clienteEmail})
|
|
</label>
|
|
)}
|
|
|
|
<div className="flex justify-end gap-2 pt-2 border-t border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowEnviarModal(false)}
|
|
disabled={loading}
|
|
className="px-3 py-2 rounded-lg border border-border text-sm hover:bg-gray-50 disabled:opacity-50"
|
|
>
|
|
Cancelar
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={loading}
|
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
|
|
>
|
|
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
|
Confirmar envío
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|