1
This commit is contained in:
@@ -0,0 +1,748 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
X,
|
||||
Check,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
Package,
|
||||
LayoutGrid,
|
||||
Settings,
|
||||
GripVertical,
|
||||
Save,
|
||||
FileDown,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { formatCurrency, FASES as FASES_LABELS } from "@/lib/calculators";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Servicio {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: string[];
|
||||
categoriaId: string | null;
|
||||
categoriaNombre: string;
|
||||
categoriaColor: string;
|
||||
variante: string | null;
|
||||
activo: boolean;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
interface Categoria {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
color: string;
|
||||
activo: boolean;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
interface FasePaqueteUI {
|
||||
id: string;
|
||||
nombre: string;
|
||||
orden: number;
|
||||
servicios: { id: string; nombre: string; precioBase: number; tipoPago: string }[];
|
||||
}
|
||||
|
||||
interface PaqueteUI {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fases: FasePaqueteUI[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
initialServicios: Servicio[];
|
||||
initialCategorias: Categoria[];
|
||||
initialPaquetes: PaqueteUI[];
|
||||
}
|
||||
|
||||
type Tab = "categorias" | "paquetes" | "servicios";
|
||||
|
||||
const FASES = FASES_LABELS;
|
||||
|
||||
export function CatalogoClient({ initialServicios, initialCategorias, initialPaquetes }: Props) {
|
||||
const [tab, setTab] = useState<Tab>("servicios");
|
||||
const [servicios, setServicios] = useState<Servicio[]>(initialServicios);
|
||||
const [categorias, setCategorias] = useState<Categoria[]>(initialCategorias);
|
||||
const [paquetes, setPaquetes] = useState<PaqueteUI[]>(initialPaquetes);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [sRes, cRes, pRes] = await Promise.all([
|
||||
fetch("/api/catalogo"),
|
||||
fetch("/api/categorias"),
|
||||
fetch("/api/paquetes"),
|
||||
]);
|
||||
if (sRes.ok) setServicios(await sRes.json());
|
||||
if (cRes.ok) setCategorias(await cRes.json());
|
||||
if (pRes.ok) setPaquetes(await pRes.json());
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setImporting(true);
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
const res = await fetch("/api/import/catalogo", { method: "POST", body: form });
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
let msg = `${data.creados} servicio(s) importado(s).`;
|
||||
if (data.omitidos > 0) msg += ` ${data.omitidos} omitido(s).`;
|
||||
if (data.errores?.length) msg += `\n\nErrores:\n${data.errores.join("\n")}`;
|
||||
alert(msg);
|
||||
await refresh();
|
||||
} else {
|
||||
alert(data.error || "Error al importar");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al importar CSV");
|
||||
} finally {
|
||||
setImporting(false);
|
||||
e.target.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const deleteCategoria = async (id: string) => {
|
||||
const res = await fetch(`/api/categorias/${id}`, { method: "DELETE" });
|
||||
if (res.ok) setCategorias((p) => p.filter((c) => c.id !== id));
|
||||
else { const e = await res.json(); alert(e.error); }
|
||||
};
|
||||
|
||||
const toggleCategoriaActivo = async (cat: Categoria) => {
|
||||
const res = await fetch(`/api/categorias/${cat.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...cat, activo: !cat.activo }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
setCategorias((p) => p.map((c) => (c.id === cat.id ? updated : c)));
|
||||
}
|
||||
};
|
||||
|
||||
const deletePaquete = async (id: string) => {
|
||||
if (!confirm("Eliminar este paquete y todas sus fases?")) return;
|
||||
const res = await fetch(`/api/paquetes/${id}`, { method: "DELETE" });
|
||||
if (res.ok) setPaquetes((p) => p.filter((pk) => pk.id !== id));
|
||||
};
|
||||
|
||||
const handleCreatePaquete = async () => {
|
||||
const nombre = prompt("Nombre del paquete:");
|
||||
if (!nombre) return;
|
||||
const res = await fetch("/api/paquetes", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ nombre, fases: [] }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const created = await res.json();
|
||||
setPaquetes((p) => [...p, { ...created, fases: [] }]);
|
||||
}
|
||||
};
|
||||
|
||||
const addFaseToPaquete = async (paqueteId: string) => {
|
||||
const nombre = prompt("Nombre de la fase:");
|
||||
if (!nombre) return;
|
||||
const pk = paquetes.find((p) => p.id === paqueteId);
|
||||
const orden = pk ? pk.fases.length : 0;
|
||||
const res = await fetch(`/api/paquetes/${paqueteId}/manage`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "addFase", nombre, orden }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const fase = await res.json();
|
||||
setPaquetes((p) =>
|
||||
p.map((pk) =>
|
||||
pk.id === paqueteId ? { ...pk, fases: [...pk.fases, { ...fase, servicios: [] }] } : pk
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteFase = async (paqueteId: string, faseId: string) => {
|
||||
if (!confirm("Eliminar esta fase?")) return;
|
||||
const res = await fetch(`/api/paquetes/${paqueteId}/manage`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "deleteFase", faseId }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setPaquetes((p) =>
|
||||
p.map((pk) =>
|
||||
pk.id === paqueteId ? { ...pk, fases: pk.fases.filter((f) => f.id !== faseId) } : pk
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const removeServFromFase = async (paqueteId: string, faseId: string, servicioId: string) => {
|
||||
const res = await fetch(`/api/paquetes/${paqueteId}/manage`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "removeServicio", servicioCatalogoId: servicioId, fasePaqueteId: faseId }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setPaquetes((p) =>
|
||||
p.map((pk) =>
|
||||
pk.id === paqueteId
|
||||
? {
|
||||
...pk,
|
||||
fases: pk.fases.map((f) =>
|
||||
f.id === faseId
|
||||
? { ...f, servicios: f.servicios.filter((s) => s.id !== servicioId) }
|
||||
: f
|
||||
),
|
||||
}
|
||||
: pk
|
||||
)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const addServToFase = async (paqueteId: string, faseId: string, servicioId: string) => {
|
||||
const res = await fetch(`/api/paquetes/${paqueteId}/manage`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "addServicio", servicioCatalogoId: servicioId, fasePaqueteId: faseId }),
|
||||
});
|
||||
if (res.ok) await refresh();
|
||||
};
|
||||
|
||||
const [addModal, setAddModal] = useState<{ paqueteId: string; faseId: string } | null>(null);
|
||||
const [servicioModal, setServicioModal] = useState<Servicio | null>(null);
|
||||
const [showNewServicio, setShowNewServicio] = useState(false);
|
||||
const [expandedPk, setExpandedPk] = useState<Set<string>>(new Set(paquetes.map((p) => p.id)));
|
||||
|
||||
const tabs: { key: Tab; label: string; icon: React.ReactNode }[] = [
|
||||
{ key: "servicios", label: "Servicios", icon: <LayoutGrid className="w-4 h-4" /> },
|
||||
{ key: "categorias", label: "Categorias", icon: <Settings className="w-4 h-4" /> },
|
||||
{ key: "paquetes", label: "Paquetes", icon: <Package className="w-4 h-4" /> },
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold">Catalogo de Servicios</h1>
|
||||
<div className="flex items-center gap-3">
|
||||
<a
|
||||
href="/api/export/catalogo/plantilla"
|
||||
download
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<FileDown className="w-4 h-4" />
|
||||
Plantilla CSV
|
||||
</a>
|
||||
<label className={`flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 transition-colors cursor-pointer ${importing ? "opacity-50 pointer-events-none" : ""}`}>
|
||||
<Upload className="w-4 h-4" />
|
||||
{importing ? "Importando..." : "Importar CSV"}
|
||||
<input type="file" accept=".csv" onChange={handleImport} className="hidden" />
|
||||
</label>
|
||||
<a
|
||||
href="/api/export/catalogo"
|
||||
download
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<FileDown className="w-4 h-4" />
|
||||
Exportar CSV
|
||||
</a>
|
||||
<button onClick={refresh} disabled={loading} className="text-xs text-muted hover:text-dark">
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Actualizar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 mb-6 bg-gray-100 p-1 rounded-lg w-fit">
|
||||
{tabs.map((t) => (
|
||||
<button
|
||||
key={t.key}
|
||||
onClick={() => setTab(t.key)}
|
||||
className={clsx(
|
||||
"flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors",
|
||||
tab === t.key ? "bg-white shadow text-dark" : "text-muted hover:text-dark"
|
||||
)}
|
||||
>
|
||||
{t.icon}{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* ── TAB: SERVICIOS (por categoria) ── */}
|
||||
{tab === "servicios" && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<p className="text-sm text-muted">{servicios.filter((s) => s.activo).length} servicios activos</p>
|
||||
<button
|
||||
onClick={() => setShowNewServicio(true)}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark"
|
||||
>
|
||||
<Plus className="w-4 h-4" /> Nuevo Servicio
|
||||
</button>
|
||||
</div>
|
||||
{categorias.filter((c) => c.activo).map((cat) => {
|
||||
const catServs = servicios.filter((s) => s.categoriaNombre === cat.nombre);
|
||||
if (!catServs.length) return null;
|
||||
return (
|
||||
<div key={cat.id} className="mb-6">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: cat.color }} />
|
||||
<h2 className="font-semibold text-lg">{cat.nombre}</h2>
|
||||
<span className="text-xs text-muted">({catServs.length})</span>
|
||||
</div>
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-4 py-3 font-medium text-muted">Servicio</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-muted">Tipo</th>
|
||||
<th className="text-left px-4 py-3 font-medium text-muted">Tiempo</th>
|
||||
<th className="text-right px-4 py-3 font-medium text-muted">Precio</th>
|
||||
<th className="text-center px-4 py-3 font-medium text-muted">Entregables</th>
|
||||
<th className="text-center px-4 py-3 font-medium text-muted w-24">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{catServs.map((s) => (
|
||||
<tr key={s.id} className={clsx("border-b border-border hover:bg-gray-50", !s.activo && "opacity-50")}>
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium">{s.nombre}</div>
|
||||
{s.descripcion && <div className="text-xs text-muted mt-0.5">{s.descripcion}</div>}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={clsx("inline-block px-2 py-0.5 rounded text-xs font-medium", s.tipoPago === "unico" ? "bg-blue-100 text-blue-700" : "bg-green-100 text-green-700")}>
|
||||
{s.tipoPago === "unico" ? "Unico" : "Mensual"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted text-xs">{s.tiempoEntrega}</td>
|
||||
<td className="px-4 py-3 text-right font-medium">{formatCurrency(s.precioBase)}</td>
|
||||
<td className="px-4 py-3 text-center text-muted">{s.entregablesDefault.length}</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<button onClick={() => setServicioModal(s)} className="p-1.5 text-muted hover:text-primary rounded" title="Editar">
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={async () => {
|
||||
if (!confirm(`Eliminar "${s.nombre}"?`)) return;
|
||||
const res = await fetch(`/api/catalogo/${s.id}`, { method: "DELETE" });
|
||||
if (res.ok) { const d = await res.json(); if (d.archived) { setServicios((p) => p.map((x) => x.id === s.id ? { ...x, activo: false } : x)); } else { setServicios((p) => p.filter((x) => x.id !== s.id)); } }
|
||||
}} className="p-1.5 text-muted hover:text-red-500 rounded" title="Eliminar">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── TAB: CATEGORIAS ── */}
|
||||
{tab === "categorias" && (
|
||||
<div className="space-y-3">
|
||||
{categorias.map((cat) => (
|
||||
<div key={cat.id} className="bg-card-bg rounded-xl border border-border p-4 flex items-center gap-4">
|
||||
<div className="w-5 h-5 rounded-full shrink-0" style={{ backgroundColor: cat.color }} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium">{cat.nombre}</div>
|
||||
{cat.descripcion && <div className="text-xs text-muted">{cat.descripcion}</div>}
|
||||
</div>
|
||||
<span className="text-xs text-muted">
|
||||
{servicios.filter((s) => s.categoriaNombre === cat.nombre).length} servicios
|
||||
</span>
|
||||
<button
|
||||
onClick={() => toggleCategoriaActivo(cat)}
|
||||
className={clsx("px-3 py-1 rounded text-xs font-medium", cat.activo ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500")}
|
||||
>
|
||||
{cat.activo ? "Activa" : "Inactiva"}
|
||||
</button>
|
||||
<button onClick={() => deleteCategoria(cat.id)} className="p-1.5 text-muted hover:text-red-500 rounded">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<CreateCategoriaInline onCreated={refresh} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── TAB: PAQUETES ── */}
|
||||
{tab === "paquetes" && (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-end">
|
||||
<button onClick={handleCreatePaquete} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark">
|
||||
<Plus className="w-4 h-4" /> Nuevo Paquete
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{paquetes.map((pk) => {
|
||||
const isOpen = expandedPk.has(pk.id);
|
||||
return (
|
||||
<div key={pk.id} className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<div
|
||||
onClick={() => setExpandedPk((prev) => { const n = new Set(prev); n.has(pk.id) ? n.delete(pk.id) : n.add(pk.id); return n; })}
|
||||
className="w-full flex items-center gap-3 px-5 py-4 text-left hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
{isOpen ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
|
||||
<div className="flex-1">
|
||||
<div className="font-semibold text-lg">{pk.nombre}</div>
|
||||
{pk.descripcion && <div className="text-xs text-muted">{pk.descripcion}</div>}
|
||||
</div>
|
||||
<span className="text-xs text-muted">{pk.fases.length} fases</span>
|
||||
<button onClick={(e) => { e.stopPropagation(); deletePaquete(pk.id); }} className="p-1.5 text-muted hover:text-red-500 rounded">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<div className="px-5 pb-4 space-y-4">
|
||||
{pk.fases.map((fase) => (
|
||||
<div key={fase.id} className="border border-border rounded-lg overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-4 py-2 bg-gray-50">
|
||||
<span className="font-medium text-sm">{fase.nombre}</span>
|
||||
<span className="text-xs text-muted">({fase.servicios.length} servicios)</span>
|
||||
<div className="ml-auto">
|
||||
<button onClick={() => setAddModal({ paqueteId: pk.id, faseId: fase.id })} className="text-xs text-primary hover:underline mr-3">
|
||||
+ Agregar servicio
|
||||
</button>
|
||||
<button onClick={() => deleteFase(pk.id, fase.id)} className="text-xs text-red-500 hover:underline">
|
||||
Eliminar fase
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{fase.servicios.length > 0 ? (
|
||||
<table className="w-full text-sm">
|
||||
<tbody>
|
||||
{fase.servicios.map((s) => (
|
||||
<tr key={s.id} className="border-t border-border">
|
||||
<td className="px-4 py-2">
|
||||
<div className="font-medium">{s.nombre}</div>
|
||||
</td>
|
||||
<td className="px-4 py-2">
|
||||
<span className={clsx("text-xs px-2 py-0.5 rounded", s.tipoPago === "unico" ? "bg-blue-100 text-blue-700" : "bg-green-100 text-green-700")}>
|
||||
{s.tipoPago === "unico" ? "Unico" : "Mensual"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right font-medium text-sm">{formatCurrency(s.precioBase)}</td>
|
||||
<td className="px-4 py-2 w-10">
|
||||
<button onClick={() => removeServFromFase(pk.id, fase.id, s.id)} className="text-muted hover:text-red-500">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<p className="px-4 py-3 text-xs text-muted">Sin servicios asignados</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button onClick={() => addFaseToPaquete(pk.id)} className="text-sm text-primary hover:underline flex items-center gap-1">
|
||||
<Plus className="w-3.5 h-3.5" /> Agregar fase
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── MODAL: Add service to phase ── */}
|
||||
{addModal && (
|
||||
<AddServicioModal
|
||||
servicios={servicios.filter((s) => s.activo)}
|
||||
onAdd={(servicioId) => {
|
||||
addServToFase(addModal.paqueteId, addModal.faseId, servicioId);
|
||||
setAddModal(null);
|
||||
}}
|
||||
onClose={() => setAddModal(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(servicioModal || showNewServicio) && (
|
||||
<ServicioFormModal
|
||||
servicio={servicioModal}
|
||||
categorias={categorias}
|
||||
onSave={async (data) => {
|
||||
if (servicioModal) {
|
||||
const res = await fetch(`/api/catalogo/${servicioModal.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const updated = await res.json();
|
||||
setServicios((p) => p.map((s) => (s.id === servicioModal.id ? { ...s, ...updated, categoriaNombre: categorias.find((c) => c.id === data.categoriaId)?.nombre || s.categoriaNombre, categoriaColor: categorias.find((c) => c.id === data.categoriaId)?.color || s.categoriaColor } : s)));
|
||||
}
|
||||
} else {
|
||||
const res = await fetch("/api/catalogo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (res.ok) {
|
||||
const created = await res.json();
|
||||
const cat = categorias.find((c) => c.id === data.categoriaId);
|
||||
setServicios((p) => [...p, { ...created, categoriaNombre: cat?.nombre || "Sin categoria", categoriaColor: cat?.color || "#6b7280" }]);
|
||||
}
|
||||
}
|
||||
setServicioModal(null);
|
||||
setShowNewServicio(false);
|
||||
}}
|
||||
onClose={() => { setServicioModal(null); setShowNewServicio(false); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateCategoriaInline({ onCreated }: { onCreated: () => void }) {
|
||||
const [nombre, setNombre] = useState("");
|
||||
const [color, setColor] = useState("#6b7280");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!nombre.trim()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/api/categorias", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ nombre: nombre.trim(), color }),
|
||||
});
|
||||
if (res.ok) { setNombre(""); onCreated(); }
|
||||
else { const e = await res.json(); alert(e.error); }
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 bg-card-bg rounded-xl border border-dashed border-border p-4">
|
||||
<input type="color" value={color} onChange={(e) => setColor(e.target.value)} className="w-8 h-8 rounded cursor-pointer p-0 border-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={nombre}
|
||||
onChange={(e) => setNombre(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleSave()}
|
||||
placeholder="Nueva categoria..."
|
||||
className="flex-1 px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
<button onClick={handleSave} disabled={saving || !nombre.trim()} className="flex items-center gap-2 px-3 py-2 bg-primary text-white rounded-lg text-sm disabled:opacity-50">
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}
|
||||
Crear
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddServicioModal({
|
||||
servicios,
|
||||
onAdd,
|
||||
onClose,
|
||||
}: {
|
||||
servicios: Servicio[];
|
||||
onAdd: (id: string) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const filtered = servicios.filter(
|
||||
(s) =>
|
||||
s.nombre.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.categoriaNombre.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[70vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h3 className="font-semibold">Agregar servicio a la fase</h3>
|
||||
<button onClick={onClose}><X className="w-5 h-5 text-muted" /></button>
|
||||
</div>
|
||||
<div className="px-5 py-3 border-b border-border">
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Buscar por nombre o categoria..."
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1">
|
||||
{filtered.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => onAdd(s.id)}
|
||||
className="w-full text-left px-5 py-3 hover:bg-gray-50 border-b border-border/50 flex items-center gap-3"
|
||||
>
|
||||
<div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: s.categoriaColor }} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm truncate">{s.nombre}</div>
|
||||
<div className="text-xs text-muted">{s.categoriaNombre} · {s.tipoPago === "unico" ? "Unico" : "Mensual"}</div>
|
||||
</div>
|
||||
<span className="text-sm font-medium">{formatCurrency(s.precioBase)}</span>
|
||||
</button>
|
||||
))}
|
||||
{filtered.length === 0 && <p className="text-center text-muted text-sm py-8">Sin resultados</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ServicioFormModal({
|
||||
servicio,
|
||||
categorias,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
servicio: Servicio | null;
|
||||
categorias: Categoria[];
|
||||
onSave: (data: Record<string, unknown>) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [form, setForm] = useState({
|
||||
nombre: servicio?.nombre || "",
|
||||
descripcion: servicio?.descripcion || "",
|
||||
categoriaId: servicio?.categoriaId || "",
|
||||
tipoPago: servicio?.tipoPago || "unico",
|
||||
precioBase: servicio?.precioBase ?? 0,
|
||||
tiempoEntrega: servicio?.tiempoEntrega || "4 - 10 dias",
|
||||
entregablesDefault: servicio?.entregablesDefault?.join("\n") || "",
|
||||
variante: servicio?.variante || "",
|
||||
fase: servicio?.fase ?? 1,
|
||||
orden: servicio?.orden ?? 0,
|
||||
activo: servicio?.activo ?? true,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.nombre.trim()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const entregables = form.entregablesDefault
|
||||
.split("\n")
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
const cat = categorias.find((c) => c.id === form.categoriaId);
|
||||
await onSave({
|
||||
nombre: form.nombre.trim(),
|
||||
descripcion: form.descripcion.trim() || null,
|
||||
categoriaId: form.categoriaId || null,
|
||||
tipoPago: form.tipoPago,
|
||||
precioBase: Number(form.precioBase),
|
||||
tiempoEntrega: form.tiempoEntrega,
|
||||
entregablesDefault: entregables,
|
||||
variante: form.variante.trim() || null,
|
||||
fase: form.fase,
|
||||
orden: form.orden,
|
||||
activo: form.activo,
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const update = (key: string, value: unknown) => setForm((p) => ({ ...p, [key]: value }));
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={onClose}>
|
||||
<div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[85vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h3 className="font-semibold">{servicio ? "Editar Servicio" : "Nuevo Servicio"}</h3>
|
||||
<button onClick={onClose}><X className="w-5 h-5 text-muted" /></button>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1 p-5 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Nombre *</label>
|
||||
<input type="text" value={form.nombre} onChange={(e) => update("nombre", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Descripcion</label>
|
||||
<textarea value={form.descripcion} onChange={(e) => update("descripcion", e.target.value)} rows={2} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Categoria</label>
|
||||
<select value={form.categoriaId} onChange={(e) => update("categoriaId", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
<option value="">Sin categoria</option>
|
||||
{categorias.map((c) => <option key={c.id} value={c.id}>{c.nombre}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tipo de Pago</label>
|
||||
<select value={form.tipoPago} onChange={(e) => update("tipoPago", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
<option value="unico">Unico</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Precio Base</label>
|
||||
<input type="number" value={form.precioBase} onChange={(e) => update("precioBase", Number(e.target.value))} min={0} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Fase</label>
|
||||
<select value={form.fase} onChange={(e) => update("fase", Number(e.target.value))} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary bg-white">
|
||||
{Object.entries(FASES).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Tiempo Entrega</label>
|
||||
<input type="text" value={form.tiempoEntrega} onChange={(e) => update("tiempoEntrega", e.target.value)} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Entregables (uno por linea)</label>
|
||||
<textarea value={form.entregablesDefault} onChange={(e) => update("entregablesDefault", e.target.value)} rows={4} placeholder="Entregable 1 Entregable 2 ..." className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none font-mono text-xs" />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Variante</label>
|
||||
<input type="text" value={form.variante} onChange={(e) => update("variante", e.target.value)} placeholder="Ej: WooCommerce, Shopify..." className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Orden</label>
|
||||
<input type="number" value={form.orden} onChange={(e) => update("orden", Number(e.target.value))} min={0} className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={form.activo} onChange={(e) => update("activo", e.target.checked)} className="rounded border-border" />
|
||||
Activo
|
||||
</label>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-3">
|
||||
<button onClick={onClose} className="px-4 py-2 border border-border rounded-lg text-sm hover:bg-gray-50">Cancelar</button>
|
||||
<button onClick={handleSave} disabled={saving || !form.nombre.trim()} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium disabled:opacity-50 hover:bg-primary-dark">
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{servicio ? "Guardar Cambios" : "Crear Servicio"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { CatalogoClient } from "./CatalogoClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function CatalogoPage() {
|
||||
const [servicios, categorias, paquetes] = await Promise.all([
|
||||
prisma.servicioCatalogo.findMany({
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
include: { categoriaRel: true, paquetes: { include: { fasePaquete: true } } },
|
||||
}),
|
||||
prisma.categoria.findMany({ orderBy: { orden: "asc" } }),
|
||||
prisma.paquete.findMany({
|
||||
where: { activo: true },
|
||||
include: {
|
||||
fases: {
|
||||
orderBy: { orden: "asc" },
|
||||
include: {
|
||||
servicios: { include: { servicio: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
return (
|
||||
<CatalogoClient
|
||||
initialServicios={servicios.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.nombre,
|
||||
descripcion: s.descripcion,
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precioBase: s.precioBase,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregablesDefault: Array.isArray(s.entregablesDefault) ? (s.entregablesDefault as string[]) : [],
|
||||
categoriaId: s.categoriaId,
|
||||
categoriaNombre: s.categoriaRel?.nombre || "Sin categoria",
|
||||
categoriaColor: s.categoriaRel?.color || "#6b7280",
|
||||
variante: s.variante,
|
||||
activo: s.activo,
|
||||
orden: s.orden,
|
||||
}))}
|
||||
initialCategorias={categorias}
|
||||
initialPaquetes={paquetes.map((p) => ({
|
||||
id: p.id,
|
||||
nombre: p.nombre,
|
||||
descripcion: p.descripcion,
|
||||
fases: p.fases.map((f) => ({
|
||||
id: f.id,
|
||||
nombre: f.nombre,
|
||||
orden: f.orden,
|
||||
servicios: f.servicios.map((sp) => sp.servicio),
|
||||
})),
|
||||
}))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Search } from "lucide-react";
|
||||
import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton";
|
||||
|
||||
interface Cliente {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
cotizaciones: { id: string }[];
|
||||
}
|
||||
|
||||
export function ClientesList({ clientes }: { clientes: Cliente[] }) {
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const filtered = clientes.filter((c) => {
|
||||
if (!search) return true;
|
||||
const q = search.toLowerCase();
|
||||
return (
|
||||
c.nombre.toLowerCase().includes(q) ||
|
||||
(c.empresa || "").toLowerCase().includes(q) ||
|
||||
(c.email || "").toLowerCase().includes(q)
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<div className="relative max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Buscar por nombre, empresa, email..."
|
||||
className="w-full pl-10 pr-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<p className="text-center text-muted py-8">
|
||||
{search ? "Sin resultados para esa busqueda" : "No hay clientes"}
|
||||
</p>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Nombre
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Empresa
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Email
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Telefono
|
||||
</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">
|
||||
Cotizaciones
|
||||
</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted w-16" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((c) => (
|
||||
<tr
|
||||
key={c.id}
|
||||
className="border-b border-border hover:bg-gray-50"
|
||||
>
|
||||
<td className="px-5 py-3 font-medium">{c.nombre}</td>
|
||||
<td className="px-5 py-3">{c.empresa || "-"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.email || "-"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.telefono || "-"}</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<span className="inline-block px-2 py-0.5 bg-primary-light text-primary rounded text-xs font-medium">
|
||||
{c.cotizaciones.length}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<NuevaCotizacionClienteButton
|
||||
clienteNombre={c.nombre}
|
||||
clienteEmpresa={c.empresa || ""}
|
||||
clienteEmail={c.email || ""}
|
||||
clienteTelefono={c.telefono || ""}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Plus } from "lucide-react";
|
||||
import { useCotizacionStore } from "@/lib/store";
|
||||
|
||||
export function NuevaCotizacionClienteButton({
|
||||
clienteNombre,
|
||||
clienteEmpresa,
|
||||
clienteEmail,
|
||||
clienteTelefono,
|
||||
}: {
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
clienteEmail: string;
|
||||
clienteTelefono: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const store = useCotizacionStore();
|
||||
|
||||
const handleClick = () => {
|
||||
store.resetDraft();
|
||||
store.setField("clienteNombre", clienteNombre);
|
||||
store.setField("clienteEmpresa", clienteEmpresa);
|
||||
store.setField("clienteEmail", clienteEmail);
|
||||
store.setField("clienteTelefono", clienteTelefono);
|
||||
router.push("/cotizaciones/nueva");
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="p-1.5 text-muted hover:text-primary hover:bg-primary/5 rounded transition-colors"
|
||||
title="Nueva cotizacion"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ClientesPage() {
|
||||
const clientes = await prisma.cliente.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { cotizaciones: { select: { id: true } } },
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Clientes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{clientes.length} clientes registrados
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{clientes.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h2 className="text-lg font-semibold mb-2">No hay clientes</h2>
|
||||
<p className="text-muted mb-4">
|
||||
Los clientes se crean automaticamente al generar cotizaciones
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ClientesListWrapper clientes={clientes} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
import { ClientesList } from "./ClientesList";
|
||||
|
||||
function ClientesListWrapper({
|
||||
clientes,
|
||||
}: {
|
||||
clientes: {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
cotizaciones: { id: string }[];
|
||||
}[];
|
||||
}) {
|
||||
return <ClientesList clientes={clientes} />;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { Save, Upload, Trash2, Loader2, Image } from "lucide-react";
|
||||
|
||||
const SECTIONS = [
|
||||
{
|
||||
title: "Branding",
|
||||
icon: "🎨",
|
||||
fields: [
|
||||
{ key: "color_primario", label: "Color Primario", type: "color" },
|
||||
{ key: "color_secundario", label: "Color Secundario", type: "color" },
|
||||
],
|
||||
hasLogo: true,
|
||||
},
|
||||
{
|
||||
title: "Datos Fiscales",
|
||||
icon: "📋",
|
||||
fields: [
|
||||
{ key: "razon_social", label: "Razon Social", type: "text" },
|
||||
{ key: "rfc", label: "RFC", type: "text" },
|
||||
{ key: "domicilio_fiscal", label: "Domicilio Fiscal", type: "text" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Datos Bancarios Nacionales",
|
||||
icon: "🏦",
|
||||
fields: [
|
||||
{ key: "cuenta_nacional", label: "Cuenta", type: "text" },
|
||||
{ key: "clabe_interbancaria", label: "CLABE Interbancaria", type: "text" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Datos Bancarios Internacionales",
|
||||
icon: "🌎",
|
||||
fields: [
|
||||
{ key: "cuenta_internacional", label: "Transferencia Internacional (ABA)", type: "textarea" },
|
||||
{ key: "cuenta_internacional_swift", label: "Transferencia Internacional (SWIFT)", type: "textarea" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Configuracion del Sistema",
|
||||
icon: "⚙️",
|
||||
fields: [
|
||||
{ key: "hora_centinela", label: "Precio Hora Centinela (MXN)", type: "text" },
|
||||
{ key: "anualidad_hosting", label: "Anualidad Hosting (MXN)", type: "text" },
|
||||
{ key: "iva", label: "IVA (decimal)", type: "text" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Textos Legales",
|
||||
icon: "📜",
|
||||
fields: [
|
||||
{ key: "terminos_condiciones", label: "Terminos y Condiciones", type: "textarea" },
|
||||
{ key: "no_incluye", label: "Que No Incluye", type: "textarea" },
|
||||
{ key: "notas_adicionales", label: "Notas Adicionales", type: "textarea" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function ConfiguracionClient({ initial }: { initial: Record<string, string> }) {
|
||||
const [config, setConfig] = useState<Record<string, string>>(initial);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleChange = (key: string, value: string) => {
|
||||
setConfig((prev) => ({ ...prev, [key]: value }));
|
||||
setSaved(false);
|
||||
};
|
||||
|
||||
const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (file.size > 500 * 1024) {
|
||||
alert("El logo debe ser menor a 500KB");
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const result = reader.result as string;
|
||||
const base64 = result.split(",")[1];
|
||||
handleChange("logo_base64", `${file.type}:${base64}`);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const handleRemoveLogo = () => {
|
||||
handleChange("logo_base64", "");
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch("/api/configuracion", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
if (res.ok) {
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} else {
|
||||
alert("Error al guardar");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al guardar");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Configuracion</h1>
|
||||
<p className="text-muted text-sm mt-1">Personaliza el branding y datos de tu empresa</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="flex items-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark disabled:opacity-50 transition-colors font-medium text-sm"
|
||||
>
|
||||
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
|
||||
{saving ? "Guardando..." : saved ? "Guardado!" : "Guardar Cambios"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{SECTIONS.map((section) => (
|
||||
<div key={section.title} className="bg-card-bg rounded-xl border border-border">
|
||||
<div className="px-5 py-4 border-b border-border flex items-center gap-2">
|
||||
<span>{section.icon}</span>
|
||||
<h2 className="font-semibold">{section.title}</h2>
|
||||
</div>
|
||||
<div className="p-5 space-y-4">
|
||||
{section.hasLogo && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-2">Logo de la Empresa</label>
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-24 h-24 border-2 border-dashed border-border rounded-lg flex items-center justify-center bg-gray-50 shrink-0 overflow-hidden">
|
||||
{config.logo_base64 ? (
|
||||
<img
|
||||
src={config.logo_base64.includes(":") ? `data:${config.logo_base64.replace(":", ";base64,")}` : `data:image/png;base64,${config.logo_base64}`}
|
||||
alt="Logo"
|
||||
className="w-full h-full object-contain p-1"
|
||||
/>
|
||||
) : (
|
||||
<Image className="w-8 h-8 text-muted" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 space-y-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/svg+xml,image/webp"
|
||||
onChange={handleLogoUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
Subir Logo
|
||||
</button>
|
||||
{config.logo_base64 && (
|
||||
<button
|
||||
onClick={handleRemoveLogo}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-red-200 rounded-lg text-sm text-red-600 hover:bg-red-50 transition-colors"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
Eliminar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted">PNG, JPG, SVG o WebP. Maximo 500KB.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{section.fields.map((field) => (
|
||||
<div key={field.key}>
|
||||
<label className="block text-sm font-medium text-muted mb-1">{field.label}</label>
|
||||
{field.type === "color" ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
value={config[field.key] || "#2563eb"}
|
||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||
className="w-10 h-10 rounded-lg border border-border cursor-pointer p-0.5"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={config[field.key] || ""}
|
||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||
className="w-32 px-3 py-2 border border-border rounded-lg text-sm font-mono"
|
||||
/>
|
||||
<div
|
||||
className="w-8 h-8 rounded-full border border-border"
|
||||
style={{ backgroundColor: config[field.key] || "#2563eb" }}
|
||||
/>
|
||||
</div>
|
||||
) : field.type === "textarea" ? (
|
||||
<textarea
|
||||
value={config[field.key] || ""}
|
||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||
rows={6}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
value={config[field.key] || ""}
|
||||
onChange={(e) => handleChange(field.key, e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ConfiguracionClient } from "./ConfiguracionClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ConfiguracionPage() {
|
||||
const configs = await prisma.configuracion.findMany();
|
||||
const map: Record<string, string> = {};
|
||||
for (const c of configs) map[c.clave] = c.valor;
|
||||
|
||||
return <ConfiguracionClient initial={map} />;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Pencil, Search } from "lucide-react";
|
||||
import { formatDate, formatCurrency } from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
import { ListDeleteButton } from "./ListDeleteButton";
|
||||
|
||||
interface Cotizacion {
|
||||
id: string;
|
||||
numero: string;
|
||||
estado: string;
|
||||
fecha: Date;
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
asesor: { name: string };
|
||||
servicios: { tipoPago: string; seleccionado: boolean; precio: number }[];
|
||||
}
|
||||
|
||||
export function CotizacionesList({
|
||||
cotizaciones,
|
||||
}: {
|
||||
cotizaciones: Cotizacion[];
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const filtered = cotizaciones.filter((cot) => {
|
||||
if (!search) return true;
|
||||
const q = search.toLowerCase();
|
||||
return (
|
||||
cot.numero.toLowerCase().includes(q) ||
|
||||
cot.cliente.nombre.toLowerCase().includes(q) ||
|
||||
(cot.cliente.empresa || "").toLowerCase().includes(q) ||
|
||||
cot.asesor.name.toLowerCase().includes(q) ||
|
||||
cot.estado.toLowerCase().includes(q)
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<div className="relative max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
||||
<input
|
||||
type="text"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Buscar por numero, cliente, asesor..."
|
||||
className="w-full pl-10 pr-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filtered.length === 0 ? (
|
||||
<p className="text-center text-muted py-8">
|
||||
{search ? "Sin resultados para esa busqueda" : "No hay cotizaciones"}
|
||||
</p>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
No. Cotizacion
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Cliente
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Asesor
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Fecha
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Estado
|
||||
</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">
|
||||
Total Unico
|
||||
</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">
|
||||
Total Mensual
|
||||
</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">
|
||||
Acciones
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((cot) => {
|
||||
const totalUnico = cot.servicios
|
||||
.filter((s) => s.tipoPago === "unico" && s.seleccionado)
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
const totalMensual = cot.servicios
|
||||
.filter((s) => s.tipoPago === "mensual" && s.seleccionado)
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
return (
|
||||
<tr
|
||||
key={cot.id}
|
||||
className="border-b border-border hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<td className="px-5 py-3">
|
||||
<Link
|
||||
href={`/cotizaciones/${cot.id}`}
|
||||
className="text-primary font-medium hover:underline"
|
||||
>
|
||||
{cot.numero}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>
|
||||
{cot.cliente.empresa || cot.cliente.nombre}
|
||||
</div>
|
||||
<div className="text-xs text-muted">
|
||||
{cot.cliente.nombre}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-muted">
|
||||
{cot.asesor.name}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-muted">
|
||||
{formatDate(cot.fecha)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<EstadoBadge estado={cot.estado} />
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-medium">
|
||||
{totalUnico > 0 ? formatCurrency(totalUnico) : "-"}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-medium">
|
||||
{totalMensual > 0
|
||||
? formatCurrency(totalMensual)
|
||||
: "-"}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<Link
|
||||
href={`/cotizaciones/${cot.id}/editar`}
|
||||
className="text-xs text-primary hover:underline flex items-center gap-1"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
Editar
|
||||
</Link>
|
||||
<ListDeleteButton id={cot.id} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export function ListDeleteButton({ id }: { id: string }) {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const router = useRouter();
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!confirm("Eliminar esta cotizacion?")) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${id}`, { method: "DELETE" });
|
||||
if (res.ok) router.refresh();
|
||||
else alert("Error al eliminar");
|
||||
} catch {
|
||||
alert("Error al eliminar");
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
className="text-xs text-red-500 hover:text-red-700 disabled:opacity-50"
|
||||
>
|
||||
{deleting ? "..." : "Eliminar"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
const OPCIONES = [
|
||||
{ value: "borrador", label: "Borrador" },
|
||||
{ value: "enviada", label: "Enviada" },
|
||||
{ value: "aprobada", label: "Aprobada" },
|
||||
{ value: "rechazada", label: "Rechazada" },
|
||||
];
|
||||
|
||||
export function CambiarEstadoButtons({ cotizacionId, estado }: { cotizacionId: string; estado: string }) {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleChange = async (nuevoEstado: string) => {
|
||||
if (nuevoEstado === estado) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ estado: nuevoEstado }),
|
||||
});
|
||||
if (res.ok) router.refresh();
|
||||
else alert("Error al cambiar estado");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<select
|
||||
value={estado}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
disabled={loading}
|
||||
className="text-xs font-medium px-2 py-1 rounded-full border border-border bg-white focus:outline-none focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
|
||||
>
|
||||
{OPCIONES.map((o) => (
|
||||
<option key={o.value} value={o.value}>{o.label}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
export function DeleteCotizacionButton({
|
||||
cotizacionId,
|
||||
cotizacionNumero,
|
||||
}: {
|
||||
cotizacionId: string;
|
||||
cotizacionNumero: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (res.ok) {
|
||||
router.push("/cotizaciones");
|
||||
} else {
|
||||
alert("Error al eliminar");
|
||||
setConfirming(false);
|
||||
}
|
||||
} catch {
|
||||
alert("Error al eliminar");
|
||||
setConfirming(false);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (confirming) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-red-600 font-medium">
|
||||
Eliminar {cotizacionNumero}?
|
||||
</span>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
className="px-3 py-2 bg-red-600 text-white rounded-lg text-sm hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{deleting ? "Eliminando..." : "Si, eliminar"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setConfirming(false)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => setConfirming(true)}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-red-200 rounded-lg text-sm text-red-600 hover:bg-red-50"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
Eliminar
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { formatCurrency, IVA_RATE } from "@/lib/calculators";
|
||||
|
||||
interface ServicioItem {
|
||||
id: string;
|
||||
nombre: string;
|
||||
precio: number;
|
||||
}
|
||||
|
||||
interface PreciosEditablesProps {
|
||||
cotizacionId: string;
|
||||
serviciosUnicos: ServicioItem[];
|
||||
serviciosMensuales: ServicioItem[];
|
||||
}
|
||||
|
||||
const INPUT_CLS =
|
||||
"w-28 px-2 py-1 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary";
|
||||
|
||||
export function PreciosEditables({
|
||||
cotizacionId,
|
||||
serviciosUnicos,
|
||||
serviciosMensuales,
|
||||
}: PreciosEditablesProps) {
|
||||
const [unicos, setUnicos] = useState(serviciosUnicos);
|
||||
const [mensuales, setMensuales] = useState(serviciosMensuales);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
|
||||
const totalUnico = unicos.reduce((s, x) => s + x.precio, 0);
|
||||
const totalMensual = mensuales.reduce((s, x) => s + x.precio, 0);
|
||||
|
||||
const handlePrecioChange = async (
|
||||
servicioId: string,
|
||||
nuevoPrecio: number,
|
||||
tipo: "unico" | "mensual"
|
||||
) => {
|
||||
const lista = tipo === "unico" ? unicos : mensuales;
|
||||
const setter = tipo === "unico" ? setUnicos : setMensuales;
|
||||
const prev = lista;
|
||||
|
||||
setter(lista.map((s) => (s.id === servicioId ? { ...s, precio: nuevoPrecio } : s)));
|
||||
|
||||
setSaving(servicioId);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/precio`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ servicioId, precio: nuevoPrecio }),
|
||||
});
|
||||
if (!res.ok) setter(prev);
|
||||
} catch {
|
||||
setter(prev);
|
||||
} finally {
|
||||
setSaving(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-card-bg rounded-xl border border-border">
|
||||
<div className="px-5 py-4 border-b border-border">
|
||||
<h3 className="font-semibold">Pago Unico</h3>
|
||||
</div>
|
||||
<div className="p-5">
|
||||
{unicos.length === 0 ? (
|
||||
<p className="text-muted text-sm">Sin servicios</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{unicos.map((s) => (
|
||||
<div key={s.id} className="flex items-center justify-between text-sm gap-2">
|
||||
<span className="flex-1 truncate">{s.nombre}</span>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<span className="text-muted text-xs">$</span>
|
||||
<input
|
||||
type="number"
|
||||
value={s.precio}
|
||||
onChange={(e) =>
|
||||
handlePrecioChange(s.id, parseFloat(e.target.value) || 0, "unico")
|
||||
}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
{saving === s.id && (
|
||||
<span className="text-xs text-muted">...</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="border-t border-border mt-3 pt-3 space-y-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Subtotal</span>
|
||||
<span>{formatCurrency(totalUnico)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm text-muted">
|
||||
<span>IVA (16%)</span>
|
||||
<span>{formatCurrency(totalUnico * IVA_RATE)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm font-bold pt-2 border-t border-border">
|
||||
<span>Total</span>
|
||||
<span className="text-primary">
|
||||
{formatCurrency(totalUnico * (1 + IVA_RATE))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-card-bg rounded-xl border border-border">
|
||||
<div className="px-5 py-4 border-b border-border">
|
||||
<h3 className="font-semibold">Pago Mensual</h3>
|
||||
</div>
|
||||
<div className="p-5">
|
||||
{mensuales.length === 0 ? (
|
||||
<p className="text-muted text-sm">Sin servicios</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{mensuales.map((s) => (
|
||||
<div key={s.id} className="flex items-center justify-between text-sm gap-2">
|
||||
<span className="flex-1 truncate">{s.nombre}</span>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<span className="text-muted text-xs">$</span>
|
||||
<input
|
||||
type="number"
|
||||
value={s.precio}
|
||||
onChange={(e) =>
|
||||
handlePrecioChange(s.id, parseFloat(e.target.value) || 0, "mensual")
|
||||
}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
{saving === s.id && (
|
||||
<span className="text-xs text-muted">...</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="border-t border-border mt-3 pt-3 space-y-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Subtotal</span>
|
||||
<span>{formatCurrency(totalMensual)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm text-muted">
|
||||
<span>IVA (16%)</span>
|
||||
<span>{formatCurrency(totalMensual * IVA_RATE)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm font-bold pt-2 border-t border-border">
|
||||
<span>Total</span>
|
||||
<span className="text-primary">
|
||||
{formatCurrency(totalMensual * (1 + IVA_RATE))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { CotizacionForm } from "@/components/CotizacionForm";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function EditarCotizacionPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
|
||||
const [cot, servicios, asesores] = await Promise.all([
|
||||
prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
}),
|
||||
prisma.servicioCatalogo.findMany({ where: { activo: true }, orderBy: { orden: "asc" }, include: { categoriaRel: true } }),
|
||||
prisma.user.findMany({ orderBy: { name: "asc" } }),
|
||||
]);
|
||||
|
||||
if (!cot) notFound();
|
||||
|
||||
const existingData = {
|
||||
id: cot.id,
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
clienteEmpresa: cot.cliente.empresa || "",
|
||||
clienteEmail: cot.cliente.email || "",
|
||||
clienteTelefono: cot.cliente.telefono || "",
|
||||
asesorId: cot.asesorId,
|
||||
asesorNombre: cot.asesor.name,
|
||||
fecha: cot.fecha,
|
||||
vigencia: cot.vigencia,
|
||||
moneda: cot.moneda,
|
||||
tipoCambio: cot.tipoCambio,
|
||||
proyecto: cot.proyecto,
|
||||
esquemaPago: cot.esquemaPago,
|
||||
incluirBonos: cot.incluirBonos,
|
||||
incluirFinanciamiento: cot.incluirFinanciamiento,
|
||||
observaciones: cot.observaciones || "",
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||
servicios: cot.servicios.map((s) => ({
|
||||
catalogoId: s.servicioCatalogoId,
|
||||
nombre: s.servicioCatalogo?.nombre || "Servicio",
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precio,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
||||
})),
|
||||
estado: cot.estado,
|
||||
};
|
||||
|
||||
return (
|
||||
<CotizacionForm
|
||||
mode="edit"
|
||||
existingData={existingData}
|
||||
servicios={servicios.map((s) => ({
|
||||
...s,
|
||||
entregablesDefault: s.entregablesDefault as string[],
|
||||
categoriaNombre: s.categoriaRel?.nombre || "Sin categoria",
|
||||
}))}
|
||||
asesores={asesores}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { formatDate, formatCurrency, IVA_RATE } from "@/lib/calculators";
|
||||
import Link from "next/link";
|
||||
import { ArrowLeft, Pencil } from "lucide-react";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExportExcelButtonSaved, ExportPDFButtonSaved } from "@/components/ExportButtons";
|
||||
import { DeleteCotizacionButton } from "./DeleteButton";
|
||||
import { CambiarEstadoButtons } from "./CambiarEstadoButtons";
|
||||
import { PreciosEditables } from "./PreciosEditables";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function CotizacionDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!cot) notFound();
|
||||
|
||||
const serviciosUnicos = cot.servicios
|
||||
.filter((s) => s.tipoPago === "unico" && s.seleccionado)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.servicioCatalogo?.nombre || "Servicio",
|
||||
precio: s.precio,
|
||||
}));
|
||||
|
||||
const serviciosMensuales = cot.servicios
|
||||
.filter((s) => s.tipoPago === "mensual" && s.seleccionado)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.servicioCatalogo?.nombre || "Servicio",
|
||||
precio: s.precio,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link
|
||||
href="/cotizaciones"
|
||||
className="p-2 hover:bg-gray-100 rounded-lg"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{cot.numero}</h1>
|
||||
<p className="text-muted text-sm">
|
||||
{cot.cliente.empresa || cot.cliente.nombre} | {cot.proyecto}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExportPDFButtonSaved cotizacionId={cot.id} />
|
||||
<ExportExcelButtonSaved cotizacionId={cot.id} />
|
||||
<Link
|
||||
href={`/cotizaciones/${cot.id}/editar`}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
Editar
|
||||
</Link>
|
||||
<DeleteCotizacionButton cotizacionId={cot.id} cotizacionNumero={cot.numero} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Informacion de la Cotizacion</h2>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted">Cliente</span>
|
||||
<p className="font-medium">{cot.cliente.nombre}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Empresa</span>
|
||||
<p className="font-medium">{cot.cliente.empresa || "-"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Asesor</span>
|
||||
<p className="font-medium">{cot.asesor.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Fecha</span>
|
||||
<p className="font-medium">{formatDate(cot.fecha)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Vigencia</span>
|
||||
<p className="font-medium">{formatDate(cot.vigencia)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Moneda</span>
|
||||
<p className="font-medium">{cot.moneda}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Esquema</span>
|
||||
<p className="font-medium">{cot.esquemaPago}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Estado</span>
|
||||
<div className="mt-0.5">
|
||||
<CambiarEstadoButtons cotizacionId={cot.id} estado={cot.estado} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PreciosEditables
|
||||
cotizacionId={cot.id}
|
||||
serviciosUnicos={serviciosUnicos}
|
||||
serviciosMensuales={serviciosMensuales}
|
||||
/>
|
||||
|
||||
{cot.observaciones && (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5">
|
||||
<h3 className="font-semibold mb-2">Observaciones</h3>
|
||||
<p className="text-sm text-muted whitespace-pre-wrap">{cot.observaciones}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { CotizacionForm } from "@/components/CotizacionForm";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function NuevaCotizacionPage() {
|
||||
const [servicios, asesores, clientes, paquetes] = await Promise.all([
|
||||
prisma.servicioCatalogo.findMany({
|
||||
where: { activo: true },
|
||||
orderBy: { orden: "asc" },
|
||||
include: { categoriaRel: true },
|
||||
}),
|
||||
prisma.user.findMany({ orderBy: { name: "asc" } }),
|
||||
prisma.cliente.findMany({ orderBy: { nombre: "asc" } }),
|
||||
prisma.paquete.findMany({
|
||||
where: { activo: true },
|
||||
include: {
|
||||
fases: {
|
||||
orderBy: { orden: "asc" },
|
||||
include: { servicios: { include: { servicio: true } } },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
]);
|
||||
|
||||
const lastCot = await prisma.cotizacion.findFirst({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { numero: true },
|
||||
});
|
||||
|
||||
let nextSeq = 1;
|
||||
if (lastCot) {
|
||||
const match = lastCot.numero.match(/(\d+)$/);
|
||||
if (match) nextSeq = parseInt(match[1]) + 1;
|
||||
}
|
||||
|
||||
return (
|
||||
<CotizacionForm
|
||||
mode="new"
|
||||
servicios={servicios.map((s) => ({
|
||||
...s,
|
||||
entregablesDefault: s.entregablesDefault as string[],
|
||||
categoriaNombre: s.categoriaRel?.nombre || "Sin categoria",
|
||||
}))}
|
||||
asesores={asesores}
|
||||
paquetes={paquetes.map((p) => ({
|
||||
id: p.id,
|
||||
nombre: p.nombre,
|
||||
fases: p.fases.map((f) => ({
|
||||
nombre: f.nombre,
|
||||
orden: f.orden,
|
||||
servicios: f.servicios.map((sp) => ({
|
||||
id: sp.servicio.id,
|
||||
nombre: sp.servicio.nombre,
|
||||
fase: sp.servicio.fase,
|
||||
tipoPago: sp.servicio.tipoPago,
|
||||
precioBase: sp.servicio.precioBase,
|
||||
tiempoEntrega: sp.servicio.tiempoEntrega,
|
||||
entregablesDefault: Array.isArray(sp.servicio.entregablesDefault) ? sp.servicio.entregablesDefault as string[] : [],
|
||||
})),
|
||||
})),
|
||||
}))}
|
||||
nextSeq={nextSeq}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import Link from "next/link";
|
||||
import { Plus, FileText } from "lucide-react";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { CotizacionesList } from "./CotizacionesList";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function CotizacionesPage() {
|
||||
const cotizaciones = await prisma.cotizacion.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { cliente: true, asesor: true, servicios: true },
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Cotizaciones</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{cotizaciones.length} cotizaciones registradas
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/cotizaciones/nueva"
|
||||
className="flex items-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors font-medium text-sm"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nueva Cotizacion
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{cotizaciones.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<FileText className="w-16 h-16 text-muted mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold mb-2">
|
||||
No hay cotizaciones
|
||||
</h2>
|
||||
<p className="text-muted mb-4">
|
||||
Comienza creando tu primera cotizacion
|
||||
</p>
|
||||
<Link
|
||||
href="/cotizaciones/nueva"
|
||||
className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Crear Cotizacion
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<CotizacionesList cotizaciones={cotizaciones} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import Sidebar from "@/components/layout/Sidebar";
|
||||
|
||||
export default function AppLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<Sidebar />
|
||||
<main className="flex-1 lg:ml-64">
|
||||
<div className="p-4 lg:p-8 pt-16 lg:pt-8">{children}</div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function Loading() {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[60vh]">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import Link from "next/link";
|
||||
import { FileText, Plus, Users, Database } from "lucide-react";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { formatCurrency, formatDate } from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const [
|
||||
totalCotizaciones,
|
||||
cotizacionesRecientes,
|
||||
totalClientes,
|
||||
totalServicios,
|
||||
] = await Promise.all([
|
||||
prisma.cotizacion.count(),
|
||||
prisma.cotizacion.findMany({
|
||||
take: 10,
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { cliente: true, asesor: true, servicios: true },
|
||||
}),
|
||||
prisma.cliente.count(),
|
||||
prisma.servicioCatalogo.count({ where: { activo: true } }),
|
||||
]);
|
||||
|
||||
const stats = [
|
||||
{
|
||||
label: "Cotizaciones",
|
||||
value: totalCotizaciones,
|
||||
icon: FileText,
|
||||
color: "text-primary",
|
||||
bg: "bg-primary-light",
|
||||
},
|
||||
{
|
||||
label: "Clientes",
|
||||
value: totalClientes,
|
||||
icon: Users,
|
||||
color: "text-secondary",
|
||||
bg: "bg-purple-100",
|
||||
},
|
||||
{
|
||||
label: "Servicios Activos",
|
||||
value: totalServicios,
|
||||
icon: Database,
|
||||
color: "text-accent",
|
||||
bg: "bg-cyan-100",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">Dashboard</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Bienvenido al Cotizador E3
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/cotizaciones/nueva"
|
||||
className="flex items-center gap-2 px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors font-medium text-sm"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nueva Cotizacion
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
|
||||
{stats.map((stat) => (
|
||||
<div
|
||||
key={stat.label}
|
||||
className="bg-card-bg rounded-xl border border-border p-5"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`${stat.bg} p-2.5 rounded-lg`}>
|
||||
<stat.icon className={`w-5 h-5 ${stat.color}`} />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{stat.value}</p>
|
||||
<p className="text-muted text-sm">{stat.label}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border">
|
||||
<div className="px-5 py-4 border-b border-border">
|
||||
<h2 className="font-semibold text-lg">Cotizaciones Recientes</h2>
|
||||
</div>
|
||||
{cotizacionesRecientes.length === 0 ? (
|
||||
<div className="p-8 text-center">
|
||||
<FileText className="w-12 h-12 text-muted mx-auto mb-3" />
|
||||
<p className="text-muted">
|
||||
No hay cotizaciones. Crea la primera.
|
||||
</p>
|
||||
<Link
|
||||
href="/cotizaciones/nueva"
|
||||
className="inline-flex items-center gap-2 mt-4 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nueva Cotizacion
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
No.
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Cliente
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Fecha
|
||||
</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">
|
||||
Estado
|
||||
</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">
|
||||
Servicios
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{cotizacionesRecientes.map((cot) => {
|
||||
const totalUnico = cot.servicios
|
||||
.filter((s) => s.tipoPago === "unico" && s.seleccionado)
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
const totalMensual = cot.servicios
|
||||
.filter(
|
||||
(s) => s.tipoPago === "mensual" && s.seleccionado
|
||||
)
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
return (
|
||||
<tr
|
||||
key={cot.id}
|
||||
className="border-b border-border hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<td className="px-5 py-3">
|
||||
<Link
|
||||
href={`/cotizaciones/${cot.id}`}
|
||||
className="text-primary font-medium hover:underline"
|
||||
>
|
||||
{cot.numero}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{cot.cliente.empresa || cot.cliente.nombre}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-muted">
|
||||
{formatDate(cot.fecha)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<EstadoBadge estado={cot.estado} />
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-medium">
|
||||
{totalUnico > 0 && (
|
||||
<span className="block text-xs text-muted">
|
||||
Unico: {formatCurrency(totalUnico)}
|
||||
</span>
|
||||
)}
|
||||
{totalMensual > 0 && (
|
||||
<span className="block text-xs text-muted">
|
||||
Mensual: {formatCurrency(totalMensual)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { compare } from "bcryptjs";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { createSession, setSessionCookie } from "@/lib/auth";
|
||||
import { loginSchema } from "@/lib/schemas";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = loginSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const { email, password } = parsed.data;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
|
||||
if (!user || !user.password) {
|
||||
return NextResponse.json(
|
||||
{ error: "Credenciales invalidas" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const valid = await compare(password, user.password);
|
||||
if (!valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Credenciales invalidas" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const token = await createSession({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
});
|
||||
|
||||
const response = NextResponse.json({
|
||||
user: { id: user.id, name: user.name, email: user.email, role: user.role },
|
||||
});
|
||||
response.cookies.set(setSessionCookie(token));
|
||||
return response;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Error interno" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { clearSessionCookie } from "@/lib/auth";
|
||||
|
||||
export async function POST() {
|
||||
const response = NextResponse.json({ ok: true });
|
||||
response.cookies.set(clearSessionCookie());
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getSession } from "@/lib/auth";
|
||||
|
||||
export async function GET() {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: "No autenticado" }, { status: 401 });
|
||||
}
|
||||
return NextResponse.json({ user: session });
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const servicio = await prisma.servicioCatalogo.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
fase: body.fase,
|
||||
tipoPago: body.tipoPago,
|
||||
precioBase: body.precioBase,
|
||||
tiempoEntrega: body.tiempoEntrega,
|
||||
entregablesDefault: body.entregablesDefault || [],
|
||||
variante: body.variante || null,
|
||||
activo: body.activo !== false,
|
||||
orden: body.orden,
|
||||
categoriaId: body.categoriaId || null,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(servicio);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const inUse = await prisma.servicioCotizado.count({
|
||||
where: { servicioCatalogoId: id },
|
||||
});
|
||||
if (inUse > 0) {
|
||||
await prisma.servicioCatalogo.update({
|
||||
where: { id },
|
||||
data: { activo: false },
|
||||
});
|
||||
return NextResponse.json({ ok: true, archived: true });
|
||||
}
|
||||
await prisma.servicioCatalogo.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true, archived: false });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { servicioCatalogoSchema } from "@/lib/schemas";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const servicios = await prisma.servicioCatalogo.findMany({
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
});
|
||||
return NextResponse.json(servicios);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = servicioCatalogoSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const servicio = await prisma.servicioCatalogo.create({
|
||||
data: {
|
||||
nombre: parsed.data.nombre,
|
||||
descripcion: parsed.data.descripcion,
|
||||
fase: parsed.data.fase,
|
||||
tipoPago: parsed.data.tipoPago,
|
||||
precioBase: parsed.data.precioBase,
|
||||
tiempoEntrega: parsed.data.tiempoEntrega,
|
||||
entregablesDefault: parsed.data.entregablesDefault,
|
||||
categoriaId: parsed.data.categoriaId,
|
||||
variante: parsed.data.variante,
|
||||
activo: true,
|
||||
orden: parsed.data.orden,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(servicio, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const cat = await prisma.categoria.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
color: body.color,
|
||||
orden: body.orden,
|
||||
activo: body.activo !== false,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(cat);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const inUse = await prisma.servicioCatalogo.count({ where: { categoriaId: id } });
|
||||
if (inUse > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Tiene ${inUse} servicios asociados. Desactiva la categoria en su lugar.` },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
await prisma.categoria.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const cats = await prisma.categoria.findMany({ orderBy: { orden: "asc" } });
|
||||
return NextResponse.json(cats);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const cat = await prisma.categoria.create({
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
color: body.color || "#6b7280",
|
||||
orden: body.orden ?? 0,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(cat, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const configs = await prisma.configuracion.findMany();
|
||||
const map: Record<string, string> = {};
|
||||
for (const c of configs) {
|
||||
map[c.clave] = c.valor;
|
||||
}
|
||||
return NextResponse.json(map);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const body = (await request.json()) as Record<string, string>;
|
||||
|
||||
const allowedKeys = [
|
||||
"color_primario",
|
||||
"color_secundario",
|
||||
"logo_base64",
|
||||
"razon_social",
|
||||
"rfc",
|
||||
"domicilio_fiscal",
|
||||
"cuenta_nacional",
|
||||
"clabe_interbancaria",
|
||||
"cuenta_internacional",
|
||||
"cuenta_internacional_swift",
|
||||
"hora_centinela",
|
||||
"anualidad_hosting",
|
||||
"iva",
|
||||
"terminos_condiciones",
|
||||
"no_incluye",
|
||||
"notas_adicionales",
|
||||
];
|
||||
|
||||
const ops = Object.entries(body)
|
||||
.filter(([clave]) => allowedKeys.includes(clave))
|
||||
.map(([clave, valor]) =>
|
||||
prisma.configuracion.upsert({
|
||||
where: { clave },
|
||||
update: { valor },
|
||||
create: { clave, valor },
|
||||
})
|
||||
);
|
||||
|
||||
await prisma.$transaction(ops);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { z } from "zod";
|
||||
|
||||
const schema = z.object({
|
||||
servicioId: z.string().min(1),
|
||||
precio: z.number().min(0),
|
||||
});
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { servicioId, precio } = parsed.data;
|
||||
|
||||
const serv = await prisma.servicioCotizado.findFirst({
|
||||
where: { id: servicioId, cotizacionId: id },
|
||||
});
|
||||
|
||||
if (!serv) {
|
||||
return NextResponse.json({ error: "Servicio no encontrado" }, { status: 404 });
|
||||
}
|
||||
|
||||
await prisma.servicioCotizado.update({
|
||||
where: { id: servicioId },
|
||||
data: { precio },
|
||||
});
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { ESTADOS_COTIZACION } from "@/lib/calculators";
|
||||
import { cotizacionPutSchema } from "@/lib/schemas";
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({ where: { id } });
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.cotizacion.delete({ where: { id } }),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(cot);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const parsed = cotizacionPutSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const {
|
||||
fecha,
|
||||
vigencia,
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
observaciones,
|
||||
cliente,
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
const estado = body.estado;
|
||||
|
||||
const existing = await prisma.cotizacion.findUnique({ where: { id } });
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (cliente) {
|
||||
const existingCliente = await prisma.cliente.findFirst({
|
||||
where: { nombre: cliente.nombre, empresa: cliente.empresa || null },
|
||||
});
|
||||
let clienteId = existing.clienteId;
|
||||
if (existingCliente) {
|
||||
clienteId = existingCliente.id;
|
||||
await prisma.cliente.update({
|
||||
where: { id: clienteId },
|
||||
data: {
|
||||
email: cliente.email || existingCliente.email,
|
||||
telefono: cliente.telefono || existingCliente.telefono,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const newCliente = await prisma.cliente.create({
|
||||
data: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
email: cliente.email || null,
|
||||
telefono: cliente.telefono || null,
|
||||
},
|
||||
});
|
||||
clienteId = newCliente.id;
|
||||
}
|
||||
|
||||
await prisma.cotizacion.update({
|
||||
where: { id },
|
||||
data: { clienteId },
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.cotizacion.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...(fecha && { fecha: new Date(fecha) }),
|
||||
...(vigencia && { vigencia: new Date(vigencia) }),
|
||||
...(moneda && { moneda }),
|
||||
...(tipoCambio !== undefined && { tipoCambio }),
|
||||
...(proyecto && { proyecto }),
|
||||
...(esquemaPago && { esquemaPago }),
|
||||
...(incluirBonos !== undefined && { incluirBonos }),
|
||||
...(incluirFinanciamiento !== undefined && { incluirFinanciamiento }),
|
||||
...(observaciones !== undefined && { observaciones }),
|
||||
...(estado && ESTADOS_COTIZACION.includes(estado as typeof ESTADOS_COTIZACION[number]) && { estado }),
|
||||
},
|
||||
});
|
||||
|
||||
if (servicios && Array.isArray(servicios)) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.servicioCotizado.deleteMany({ where: { cotizacionId: id } });
|
||||
|
||||
for (const serv of servicios) {
|
||||
const catalogoId = serv.catalogoId?.startsWith("bucefalo-")
|
||||
? (await tx.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
}))?.id || serv.catalogoId
|
||||
: serv.catalogoId;
|
||||
|
||||
await tx.servicioCotizado.create({
|
||||
data: {
|
||||
cotizacionId: id,
|
||||
servicioCatalogoId: catalogoId,
|
||||
fase: serv.fase,
|
||||
tipoPago: serv.tipoPago,
|
||||
precio: serv.precio,
|
||||
tiempoEntrega: serv.tiempoEntrega,
|
||||
entregables: serv.entregables,
|
||||
seleccionado: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (planBucefalo) {
|
||||
await prisma.planBucefaloCotizacion.upsert({
|
||||
where: { cotizacionId: id },
|
||||
update: { nivel: planBucefalo.nivel, precio: planBucefalo.precio },
|
||||
create: {
|
||||
cotizacionId: id,
|
||||
nivel: planBucefalo.nivel,
|
||||
precio: planBucefalo.precio,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await prisma.planBucefaloCotizacion.deleteMany({ where: { cotizacionId: id } });
|
||||
}
|
||||
|
||||
const updated = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: { cliente: true, asesor: true, servicios: true },
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error updating cotizacion:", error);
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { cotizacionPostSchema } from "@/lib/schemas";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const parsed = cotizacionPostSchema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues.map((i) => i.message).join(", ") },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const {
|
||||
numero,
|
||||
fecha,
|
||||
vigencia,
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
observaciones,
|
||||
cliente,
|
||||
asesorId,
|
||||
servicios,
|
||||
planBucefalo,
|
||||
} = parsed.data;
|
||||
|
||||
let clienteRecord = await prisma.cliente.findFirst({
|
||||
where: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
},
|
||||
});
|
||||
|
||||
if (!clienteRecord) {
|
||||
clienteRecord = await prisma.cliente.create({
|
||||
data: {
|
||||
nombre: cliente.nombre,
|
||||
empresa: cliente.empresa || null,
|
||||
email: cliente.email || null,
|
||||
telefono: cliente.telefono || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const clienteIdFinal = clienteRecord.id;
|
||||
|
||||
const cotizacion = await prisma.$transaction(async (tx) => {
|
||||
const cot = await tx.cotizacion.create({
|
||||
data: {
|
||||
numero,
|
||||
fecha: new Date(fecha),
|
||||
vigencia: new Date(vigencia),
|
||||
moneda,
|
||||
tipoCambio,
|
||||
proyecto,
|
||||
esquemaPago,
|
||||
incluirBonos,
|
||||
incluirFinanciamiento,
|
||||
observaciones: observaciones || null,
|
||||
clienteId: clienteIdFinal,
|
||||
asesorId,
|
||||
estado: "borrador",
|
||||
},
|
||||
});
|
||||
|
||||
for (const servicio of servicios) {
|
||||
const catalogoId = servicio.catalogoId.startsWith("bucefalo-")
|
||||
? (await tx.servicioCatalogo.findFirst({
|
||||
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
|
||||
}))?.id || servicio.catalogoId
|
||||
: servicio.catalogoId;
|
||||
await tx.servicioCotizado.create({
|
||||
data: {
|
||||
cotizacionId: cot.id,
|
||||
servicioCatalogoId: catalogoId,
|
||||
fase: servicio.fase,
|
||||
tipoPago: servicio.tipoPago,
|
||||
precio: servicio.precio,
|
||||
tiempoEntrega: servicio.tiempoEntrega,
|
||||
entregables: servicio.entregables,
|
||||
seleccionado: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (planBucefalo) {
|
||||
await tx.planBucefaloCotizacion.create({
|
||||
data: {
|
||||
cotizacionId: cot.id,
|
||||
nivel: planBucefalo.nivel,
|
||||
precio: planBucefalo.precio,
|
||||
seleccionado: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return cot;
|
||||
});
|
||||
|
||||
return NextResponse.json(cotizacion, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
console.error("Error creating cotizacion:", error);
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const cotizaciones = await prisma.cotizacion.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(cotizaciones);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const categorias = await prisma.categoria.findMany({
|
||||
where: { activo: true },
|
||||
orderBy: { orden: "asc" },
|
||||
select: { nombre: true },
|
||||
});
|
||||
|
||||
const catList = categorias.map((c) => c.nombre).join(" / ");
|
||||
|
||||
const csv = `Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante
|
||||
"SEO On-Page Basico","SEO","Setup e Infraestructura","unico",5000,"7 - 14 dias","Auditoria SEO | Optimizacion de meta tags | Mapa del sitio",
|
||||
"Manejo de Redes Sociales","Marketing","Publicidad y Manejo","mensual",8000,"Mensual","Publicaciones semanales | Reporte mensual | Gestion de comunidad","Basico"
|
||||
"Gestion de Google Ads","Paid Media","Publicidad y Manejo","mensual",5000,"Mensual","Configuracion de campanas | Reporte semanal",
|
||||
"Sitio Web Informativo","Desarrollo Web","Setup e Infraestructura","unico",15000,"15 - 30 dias","Diseno responsivo | Hasta 5 secciones | Formulario de contacto",
|
||||
"Automatizacion Email Marketing","Automatizaciones","Publicidad y Manejo","unico",8000,"10 - 15 dias","Configuracion de flujos | Plantillas de correo | Integracion CRM",
|
||||
"CRM Basico","CRM","Publicidad y Manejo","mensual",1000,"Mensual","CRM completo segun plan contratado","basico"
|
||||
|
||||
,,,,
|
||||
"CATEGORIAS DISPONIBLES: ${catList}",,,,,
|
||||
"FASES: Auditoria / Setup e Infraestructura / Publicidad y Manejo / Contenido y SEO",,,,,
|
||||
"TIPOS DE PAGO: unico / mensual",,,,,
|
||||
"ENTREGABLES: separar con | (pipe)",,,,,
|
||||
"VARIANTE: opcional (ej: Basico, Estandar, Premium)",,,,,
|
||||
`;
|
||||
|
||||
return new NextResponse(csv, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": "attachment; filename=plantilla-catalogo.csv",
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const servicios = await prisma.servicioCatalogo.findMany({
|
||||
where: { activo: true },
|
||||
orderBy: [{ fase: "asc" }, { orden: "asc" }],
|
||||
include: { categoriaRel: true },
|
||||
});
|
||||
|
||||
const FASES: Record<number, string> = {
|
||||
0: "Auditoria",
|
||||
1: "Setup e Infraestructura",
|
||||
2: "Publicidad y Manejo",
|
||||
3: "Contenido y SEO",
|
||||
};
|
||||
|
||||
const header = "Nombre,Categoria,Fase,Tipo de Pago,Precio Base,Tiempo de Entrega,Entregables,Variante\n";
|
||||
const rows = servicios.map((s) =>
|
||||
[
|
||||
csvEscape(s.nombre),
|
||||
csvEscape(s.categoriaRel?.nombre || ""),
|
||||
csvEscape(FASES[s.fase] || `Fase ${s.fase}`),
|
||||
csvEscape(s.tipoPago === "unico" ? "Pago Unico" : "Mensual"),
|
||||
s.precioBase.toString(),
|
||||
csvEscape(s.tiempoEntrega),
|
||||
csvEscape((s.entregablesDefault as string[]).join(" | ")),
|
||||
csvEscape(s.variante || ""),
|
||||
].join(",")
|
||||
).join("\n");
|
||||
|
||||
return new NextResponse(header + rows, {
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": "attachment; filename=catalogo-servicios.csv",
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
function csvEscape(val: string): string {
|
||||
if (val.includes(",") || val.includes('"') || val.includes("\n")) {
|
||||
return `"${val.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import ExcelJS from "exceljs";
|
||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||
import { sanitizeFilename } from "@/lib/calculators";
|
||||
|
||||
function hexToArgb(hex: string): string {
|
||||
const h = hex.replace("#", "");
|
||||
return "FF" + h.toUpperCase();
|
||||
}
|
||||
|
||||
function applyThinBorder(cell: ExcelJS.Cell, color?: string) {
|
||||
const bc: Partial<ExcelJS.Border> = { style: "thin", color: { argb: color || "FFD1D5DB" } };
|
||||
cell.border = { top: bc, left: bc, bottom: bc, right: bc };
|
||||
}
|
||||
|
||||
function fillRow(ws: ExcelJS.Worksheet, row: number, startCol: string, endCol: string, argb: string) {
|
||||
for (let c = ws.getColumn(startCol).number; c <= ws.getColumn(endCol).number; c++) {
|
||||
ws.getCell(row, c).fill = { type: "pattern", pattern: "solid", fgColor: { argb } };
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "Cotizacion no encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||
const branding = await getConfigBranding();
|
||||
const bancaria = await getConfigBancaria();
|
||||
const configColor = branding.colorPrimario || "#2563eb";
|
||||
const PRIMARY = hexToArgb(configColor);
|
||||
const PRIMARY_LIGHT = hexToArgb(configColor + "18");
|
||||
const SECONDARY = hexToArgb(branding.colorSecundario || "#1e293b");
|
||||
const WHITE = "FFFFFFFF";
|
||||
const LIGHT_BG = "FFF8FAFC";
|
||||
const MUTED = "FF64748B";
|
||||
const BORDER_COLOR = "FFE2E8F0";
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = "Cotizador E3";
|
||||
workbook.created = new Date();
|
||||
|
||||
const headerFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: WHITE } };
|
||||
const labelFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: MUTED } };
|
||||
const valueFont: Partial<ExcelJS.Font> = { size: 10, name: "Calibri" };
|
||||
const boldFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri" };
|
||||
const totalFont: Partial<ExcelJS.Font> = { bold: true, size: 11, name: "Calibri" };
|
||||
const smallFont: Partial<ExcelJS.Font> = { italic: true, size: 9, name: "Calibri", color: { argb: MUTED } };
|
||||
const faseFont: Partial<ExcelJS.Font> = { bold: true, size: 11, name: "Calibri", color: { argb: PRIMARY } };
|
||||
|
||||
const ws = workbook.addWorksheet("HOJA RESUMEN");
|
||||
ws.columns = [
|
||||
{ width: 3 },
|
||||
{ width: 22 }, { width: 22 }, { width: 16 },
|
||||
{ width: 38 }, { width: 5 },
|
||||
{ width: 20 }, { width: 5 },
|
||||
{ width: 20 }, { width: 5 },
|
||||
{ width: 18 },
|
||||
];
|
||||
ws.views = [{ showGridLines: false }];
|
||||
|
||||
// ── HEADER BANNER ──
|
||||
ws.mergeCells("B2:K2");
|
||||
ws.getCell("B2").value = bancaria.razon_social || "Cotizador E3";
|
||||
ws.getCell("B2").font = { bold: true, size: 16, name: "Calibri", color: { argb: WHITE } };
|
||||
ws.getCell("B2").alignment = { vertical: "middle" };
|
||||
fillRow(ws, 2, "A", "K", PRIMARY);
|
||||
|
||||
ws.mergeCells("B3:K3");
|
||||
ws.getCell("B3").value = cot.numero;
|
||||
ws.getCell("B3").font = { bold: true, size: 11, name: "Calibri", color: { argb: WHITE } };
|
||||
ws.getCell("B3").alignment = { vertical: "middle" };
|
||||
fillRow(ws, 3, "A", "K", SECONDARY);
|
||||
|
||||
// ── CLIENTE / PROYECTO ──
|
||||
const infoStart = 5;
|
||||
const infoLabels: [string, string, string, string][] = [
|
||||
["B", "En atencion a:", "C", cot.cliente.nombre],
|
||||
["E", "Empresa:", "F", cot.cliente.empresa || "—"],
|
||||
["B", "Proyecto:", "C", cot.proyecto],
|
||||
["E", "Moneda:", "F", cot.moneda],
|
||||
["B", "Asesor:", "C", cot.asesor.name],
|
||||
["E", "Tipo de Cambio:", "F", cot.tipoCambio],
|
||||
["B", "Fecha:", "C", ""],
|
||||
["E", "Esquema de Pago:", "F", cot.esquemaPago],
|
||||
];
|
||||
|
||||
for (let i = 0; i < infoLabels.length; i += 2) {
|
||||
const r = infoStart + (i / 2);
|
||||
const [lc1, lv1, vc1, vv1] = infoLabels[i];
|
||||
const [lc2, lv2, vc2, vv2] = infoLabels[i + 1];
|
||||
|
||||
ws.getCell(`${lc1}${r}`).value = lv1;
|
||||
ws.getCell(`${lc1}${r}`).font = labelFont;
|
||||
ws.getCell(`${vc1}${r}`).value = vv1;
|
||||
ws.getCell(`${vc1}${r}`).font = valueFont;
|
||||
|
||||
ws.getCell(`${lc2}${r}`).value = lv2;
|
||||
ws.getCell(`${lc2}${r}`).font = labelFont;
|
||||
ws.getCell(`${vc2}${r}`).value = vv2;
|
||||
ws.getCell(`${vc2}${r}`).font = valueFont;
|
||||
}
|
||||
|
||||
const fechaCell = ws.getCell(`C${infoStart + 6}`);
|
||||
fechaCell.value = cot.fecha;
|
||||
fechaCell.numFmt = "DD/MM/YYYY";
|
||||
fechaCell.font = valueFont;
|
||||
|
||||
const vigenciaCell = ws.getCell(`C${infoStart + 7}`);
|
||||
ws.getCell(`B${infoStart + 7}`).value = "Vigencia:";
|
||||
ws.getCell(`B${infoStart + 7}`).font = labelFont;
|
||||
vigenciaCell.value = cot.vigencia;
|
||||
vigenciaCell.numFmt = "DD/MM/YYYY";
|
||||
vigenciaCell.font = valueFont;
|
||||
|
||||
// ── TABLA SERVICIOS ──
|
||||
const tableStart = infoStart + 9;
|
||||
const cols = ["B", "C", "D", "E", "K"];
|
||||
const headers = ["Fase", "Tipo de Pago", "Servicio", "", "Precio"];
|
||||
|
||||
ws.mergeCells(`D${tableStart}:J${tableStart}`);
|
||||
for (let i = 0; i < cols.length; i++) {
|
||||
const cell = ws.getCell(`${cols[i]}${tableStart}`);
|
||||
cell.value = headers[i];
|
||||
cell.font = headerFont;
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY } };
|
||||
cell.alignment = { horizontal: i === cols.length - 1 ? "right" : "left", vertical: "middle" };
|
||||
applyThinBorder(cell, PRIMARY);
|
||||
}
|
||||
ws.getRow(tableStart).height = 24;
|
||||
|
||||
const fases: Record<number, string> = { 0: "FASE 0", 1: "FASE 1", 2: "FASE 2", 3: "FASE 3" };
|
||||
const serviciosUnicos = cot.servicios.filter(s => s.tipoPago === "unico" && s.seleccionado);
|
||||
const serviciosMensuales = cot.servicios.filter(s => s.tipoPago === "mensual" && s.seleccionado);
|
||||
|
||||
let row = tableStart + 1;
|
||||
let currentFase = -1;
|
||||
|
||||
for (const serv of [...serviciosUnicos, ...serviciosMensuales]) {
|
||||
if (serv.fase !== currentFase) {
|
||||
currentFase = serv.fase;
|
||||
ws.mergeCells(`B${row}:K${row}`);
|
||||
ws.getCell(`B${row}`).value = fases[serv.fase] || `FASE ${serv.fase}`;
|
||||
ws.getCell(`B${row}`).font = faseFont;
|
||||
fillRow(ws, row, "B", "K", PRIMARY_LIGHT);
|
||||
row++;
|
||||
}
|
||||
|
||||
const isAlt = row % 2 === 0;
|
||||
const rowBg = isAlt ? LIGHT_BG : WHITE;
|
||||
|
||||
ws.getCell(`B${row}`).value = "";
|
||||
ws.getCell(`C${row}`).value = serv.tipoPago === "unico" ? "Unico" : "Mensual";
|
||||
ws.getCell(`C${row}`).font = valueFont;
|
||||
ws.mergeCells(`D${row}:J${row}`);
|
||||
ws.getCell(`D${row}`).value = serv.servicioCatalogo?.nombre || "Servicio";
|
||||
ws.getCell(`D${row}`).font = valueFont;
|
||||
ws.getCell(`K${row}`).value = serv.precio;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = valueFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
|
||||
for (const c of cols) {
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: rowBg } };
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), BORDER_COLOR);
|
||||
}
|
||||
row++;
|
||||
}
|
||||
|
||||
// ── TOTALES ──
|
||||
row++;
|
||||
const totalUnico = serviciosUnicos.reduce((s, x) => s + x.precio, 0);
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "Total Pago Unico";
|
||||
ws.getCell(`B${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).value = totalUnico;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row++;
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "(+ IVA)";
|
||||
ws.getCell(`B${row}`).font = { ...smallFont, italic: false };
|
||||
row++;
|
||||
|
||||
const totalMensual = serviciosMensuales.reduce((s, x) => s + x.precio, 0);
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "Total Pago Mensual";
|
||||
ws.getCell(`B${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).value = totalMensual;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row++;
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "(+ IVA)";
|
||||
ws.getCell(`B${row}`).font = { ...smallFont, italic: false };
|
||||
row += 2;
|
||||
|
||||
if (cot.planBucefalo) {
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = `CRM Bucefalo - ${cot.planBucefalo.nivel.charAt(0).toUpperCase() + cot.planBucefalo.nivel.slice(1)}`;
|
||||
ws.getCell(`B${row}`).font = boldFont;
|
||||
ws.getCell(`K${row}`).value = cot.planBucefalo.precio;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = boldFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row += 2;
|
||||
}
|
||||
|
||||
// ── NOTA AL PIE ──
|
||||
ws.mergeCells(`B${row}:K${row}`);
|
||||
ws.getCell(`B${row}`).value = "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 dias habiles.";
|
||||
ws.getCell(`B${row}`).font = smallFont;
|
||||
|
||||
// ── HOJAS DETALLADAS POR SERVICIO ──
|
||||
for (const serv of cot.servicios.filter(s => s.seleccionado)) {
|
||||
const nombre = serv.servicioCatalogo?.nombre || "Servicio";
|
||||
const safeName = nombre.substring(0, 31).replace(/[/\\*?[\]:]/g, "");
|
||||
const dw = workbook.addWorksheet(safeName);
|
||||
dw.columns = [
|
||||
{ width: 3 },
|
||||
{ width: 35 }, { width: 5 }, { width: 15 },
|
||||
{ width: 5 },
|
||||
{ width: 35 }, { width: 5 }, { width: 15 },
|
||||
{ width: 5 }, { width: 18 },
|
||||
];
|
||||
dw.views = [{ showGridLines: false }];
|
||||
|
||||
// Banner
|
||||
dw.mergeCells("B1:J1");
|
||||
dw.getCell("B1").value = `${fases[serv.fase] || "FASE " + serv.fase} — ${nombre}`;
|
||||
dw.getCell("B1").font = { bold: true, size: 14, name: "Calibri", color: { argb: WHITE } };
|
||||
dw.getCell("B1").alignment = { vertical: "middle" };
|
||||
fillRow(dw, 1, "A", "J", PRIMARY);
|
||||
dw.getRow(1).height = 30;
|
||||
|
||||
// Info
|
||||
let r = 3;
|
||||
dw.getCell(`B${r}`).value = "Cliente:";
|
||||
dw.getCell(`B${r}`).font = labelFont;
|
||||
dw.getCell(`C${r}`).value = cot.cliente.empresa || cot.cliente.nombre;
|
||||
dw.getCell(`C${r}`).font = boldFont;
|
||||
dw.getCell(`F${r}`).value = "No. Cotizacion:";
|
||||
dw.getCell(`F${r}`).font = labelFont;
|
||||
dw.getCell(`G${r}`).value = cot.numero;
|
||||
dw.getCell(`G${r}`).font = boldFont;
|
||||
r += 2;
|
||||
|
||||
// Servicio header
|
||||
dw.getCell(`B${r}`).value = "Servicio:";
|
||||
dw.getCell(`B${r}`).font = labelFont;
|
||||
dw.getCell(`C${r}`).value = nombre;
|
||||
dw.getCell(`C${r}`).font = { ...boldFont, size: 12, color: { argb: PRIMARY } };
|
||||
dw.getCell(`F${r}`).value = "Tiempo de Entrega:";
|
||||
dw.getCell(`F${r}`).font = labelFont;
|
||||
dw.getCell(`G${r}`).value = serv.tiempoEntrega;
|
||||
dw.getCell(`G${r}`).font = valueFont;
|
||||
r += 2;
|
||||
|
||||
// Tabla entregables
|
||||
const tableCols = ["B", "C"];
|
||||
const thCols = ["B", "I"];
|
||||
for (const c of thCols) {
|
||||
dw.getCell(`${c}${r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY } };
|
||||
dw.getCell(`${c}${r}`).font = headerFont;
|
||||
dw.getCell(`${c}${r}`).border = { bottom: { style: "thin", color: { argb: PRIMARY } } };
|
||||
}
|
||||
dw.getCell(`B${r}`).value = "Entregable";
|
||||
dw.getCell(`I${r}`).value = "";
|
||||
r++;
|
||||
|
||||
const entregables = Array.isArray(serv.entregables) ? serv.entregables as string[] : [];
|
||||
for (let i = 0; i < entregables.length; i++) {
|
||||
const isAlt = i % 2 === 1;
|
||||
dw.getCell(`B${i + r}`).value = `${i + 1}. ${entregables[i]}`;
|
||||
dw.getCell(`B${i + r}`).font = valueFont;
|
||||
const bg = isAlt ? LIGHT_BG : WHITE;
|
||||
for (const c of tableCols) {
|
||||
dw.getCell(`${c}${i + r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: bg } };
|
||||
}
|
||||
applyThinBorder(dw.getCell(`B${i + r}`), BORDER_COLOR);
|
||||
}
|
||||
r += entregables.length + 1;
|
||||
|
||||
// Precio
|
||||
for (const c of ["B", "I"]) {
|
||||
dw.getCell(`${c}${r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
applyThinBorder(dw.getCell(`${c}${r}`), PRIMARY);
|
||||
}
|
||||
dw.getCell(`B${r}`).value = `Total Pago ${serv.tipoPago === "unico" ? "Unico" : "Mensual"}`;
|
||||
dw.getCell(`B${r}`).font = totalFont;
|
||||
dw.getCell(`I${r}`).value = serv.precio;
|
||||
dw.getCell(`I${r}`).numFmt = '$#,##0.00';
|
||||
dw.getCell(`I${r}`).font = totalFont;
|
||||
dw.getCell(`I${r}`).alignment = { horizontal: "right" };
|
||||
r++;
|
||||
dw.getCell(`B${r}`).value = "(+ IVA)";
|
||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
||||
r += 2;
|
||||
|
||||
// Footer
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = "Esta cotizacion tiene una vigencia de 15 dias habiles. Todos los precios en MXN, precios + IVA.";
|
||||
dw.getCell(`B${r}`).font = smallFont;
|
||||
r += 2;
|
||||
|
||||
dw.getCell(`B${r}`).value = bancaria.razon_social || "Cotizador E3";
|
||||
dw.getCell(`B${r}`).font = { ...boldFont, color: { argb: PRIMARY } };
|
||||
if (bancaria.domicilio_fiscal) {
|
||||
r++;
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = bancaria.domicilio_fiscal;
|
||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename="${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}.xlsx"`,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error("Error exporting Excel:", error);
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import ExcelJS from "exceljs";
|
||||
import { calcularVigencia, bucefaloPrecio, sanitizeFilename } from "@/lib/calculators";
|
||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||
|
||||
function hexToArgb(hex: string): string {
|
||||
const h = hex.replace("#", "");
|
||||
return "FF" + h.toUpperCase();
|
||||
}
|
||||
|
||||
function applyThinBorder(cell: ExcelJS.Cell, color?: string) {
|
||||
const bc: Partial<ExcelJS.Border> = { style: "thin", color: { argb: color || "FFD1D5DB" } };
|
||||
cell.border = { top: bc, left: bc, bottom: bc, right: bc };
|
||||
}
|
||||
|
||||
function fillRow(ws: ExcelJS.Worksheet, row: number, startCol: string, endCol: string, argb: string) {
|
||||
for (let c = ws.getColumn(startCol).number; c <= ws.getColumn(endCol).number; c++) {
|
||||
ws.getCell(row, c).fill = { type: "pattern", pattern: "solid", fgColor: { argb } };
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { draft } = body as {
|
||||
draft: {
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
asesorNombre: string;
|
||||
fecha: string;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
incluirBonos: boolean;
|
||||
servicios: {
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
}[];
|
||||
planBucefaloNivel: string | null;
|
||||
observaciones: string;
|
||||
};
|
||||
};
|
||||
|
||||
const fechaCot = new Date(draft.fecha);
|
||||
const vigencia = calcularVigencia(fechaCot);
|
||||
const empresa = draft.clienteEmpresa || draft.clienteNombre;
|
||||
|
||||
const branding = await getConfigBranding();
|
||||
const bancaria = await getConfigBancaria();
|
||||
const configColor = branding.colorPrimario || "#2563eb";
|
||||
const PRIMARY = hexToArgb(configColor);
|
||||
const PRIMARY_LIGHT = hexToArgb(configColor + "18");
|
||||
const SECONDARY = hexToArgb(branding.colorSecundario || "#1e293b");
|
||||
const WHITE = "FFFFFFFF";
|
||||
const LIGHT_BG = "FFF8FAFC";
|
||||
const MUTED = "FF64748B";
|
||||
const BORDER_COLOR = "FFE2E8F0";
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = "Cotizador E3";
|
||||
workbook.created = new Date();
|
||||
|
||||
const headerFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: WHITE } };
|
||||
const labelFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri", color: { argb: MUTED } };
|
||||
const valueFont: Partial<ExcelJS.Font> = { size: 10, name: "Calibri" };
|
||||
const boldFont: Partial<ExcelJS.Font> = { bold: true, size: 10, name: "Calibri" };
|
||||
const totalFont: Partial<ExcelJS.Font> = { bold: true, size: 11, name: "Calibri" };
|
||||
const smallFont: Partial<ExcelJS.Font> = { italic: true, size: 9, name: "Calibri", color: { argb: MUTED } };
|
||||
const faseFont: Partial<ExcelJS.Font> = { bold: true, size: 11, name: "Calibri", color: { argb: PRIMARY } };
|
||||
|
||||
const ws = workbook.addWorksheet("HOJA RESUMEN");
|
||||
ws.columns = [
|
||||
{ width: 3 },
|
||||
{ width: 22 }, { width: 22 }, { width: 16 },
|
||||
{ width: 38 }, { width: 5 },
|
||||
{ width: 20 }, { width: 5 },
|
||||
{ width: 20 }, { width: 5 },
|
||||
{ width: 18 },
|
||||
];
|
||||
ws.views = [{ showGridLines: false }];
|
||||
|
||||
ws.mergeCells("B2:K2");
|
||||
ws.getCell("B2").value = bancaria.razon_social || "Cotizador E3";
|
||||
ws.getCell("B2").font = { bold: true, size: 16, name: "Calibri", color: { argb: WHITE } };
|
||||
ws.getCell("B2").alignment = { vertical: "middle" };
|
||||
fillRow(ws, 2, "A", "K", PRIMARY);
|
||||
|
||||
ws.mergeCells("B3:K3");
|
||||
ws.getCell("B3").value = "BORRADOR";
|
||||
ws.getCell("B3").font = { bold: true, size: 11, name: "Calibri", color: { argb: WHITE } };
|
||||
ws.getCell("B3").alignment = { vertical: "middle" };
|
||||
fillRow(ws, 3, "A", "K", SECONDARY);
|
||||
|
||||
const infoStart = 5;
|
||||
const infoLabels: [string, string, string, string][] = [
|
||||
["B", "En atencion a:", "C", draft.clienteNombre],
|
||||
["E", "Empresa:", "F", draft.clienteEmpresa || "—"],
|
||||
["B", "Proyecto:", "C", draft.proyecto],
|
||||
["E", "Moneda:", "F", draft.moneda],
|
||||
["B", "Asesor:", "C", draft.asesorNombre],
|
||||
["E", "Tipo de Cambio:", "F", draft.tipoCambio],
|
||||
["B", "Fecha:", "C", ""],
|
||||
["E", "Esquema de Pago:", "F", draft.esquemaPago],
|
||||
];
|
||||
|
||||
for (let i = 0; i < infoLabels.length; i += 2) {
|
||||
const r = infoStart + (i / 2);
|
||||
const [lc1, lv1, vc1, vv1] = infoLabels[i];
|
||||
const [lc2, lv2, vc2, vv2] = infoLabels[i + 1];
|
||||
|
||||
ws.getCell(`${lc1}${r}`).value = lv1;
|
||||
ws.getCell(`${lc1}${r}`).font = labelFont;
|
||||
ws.getCell(`${vc1}${r}`).value = vv1;
|
||||
ws.getCell(`${vc1}${r}`).font = valueFont;
|
||||
|
||||
ws.getCell(`${lc2}${r}`).value = lv2;
|
||||
ws.getCell(`${lc2}${r}`).font = labelFont;
|
||||
ws.getCell(`${vc2}${r}`).value = vv2;
|
||||
ws.getCell(`${vc2}${r}`).font = valueFont;
|
||||
}
|
||||
|
||||
const fechaCell = ws.getCell(`C${infoStart + 6}`);
|
||||
fechaCell.value = fechaCot;
|
||||
fechaCell.numFmt = "DD/MM/YYYY";
|
||||
fechaCell.font = valueFont;
|
||||
|
||||
ws.getCell(`B${infoStart + 7}`).value = "Vigencia:";
|
||||
ws.getCell(`B${infoStart + 7}`).font = labelFont;
|
||||
const vigenciaCell = ws.getCell(`C${infoStart + 7}`);
|
||||
vigenciaCell.value = vigencia;
|
||||
vigenciaCell.numFmt = "DD/MM/YYYY";
|
||||
vigenciaCell.font = valueFont;
|
||||
|
||||
const tableStart = infoStart + 9;
|
||||
const cols = ["B", "C", "D", "E", "K"];
|
||||
const headers = ["Fase", "Tipo de Pago", "Servicio", "", "Precio"];
|
||||
|
||||
ws.mergeCells(`D${tableStart}:J${tableStart}`);
|
||||
for (let i = 0; i < cols.length; i++) {
|
||||
const cell = ws.getCell(`${cols[i]}${tableStart}`);
|
||||
cell.value = headers[i];
|
||||
cell.font = headerFont;
|
||||
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY } };
|
||||
cell.alignment = { horizontal: i === cols.length - 1 ? "right" : "left", vertical: "middle" };
|
||||
applyThinBorder(cell, PRIMARY);
|
||||
}
|
||||
ws.getRow(tableStart).height = 24;
|
||||
|
||||
const fases: Record<number, string> = { 0: "FASE 0", 1: "FASE 1", 2: "FASE 2", 3: "FASE 3" };
|
||||
const serviciosUnicos = draft.servicios.filter(s => s.tipoPago === "unico");
|
||||
const serviciosMensuales = draft.servicios.filter(s => s.tipoPago === "mensual");
|
||||
|
||||
let row = tableStart + 1;
|
||||
let currentFase = -1;
|
||||
|
||||
for (const serv of [...serviciosUnicos, ...serviciosMensuales]) {
|
||||
if (serv.fase !== currentFase) {
|
||||
currentFase = serv.fase;
|
||||
ws.mergeCells(`B${row}:K${row}`);
|
||||
ws.getCell(`B${row}`).value = fases[serv.fase] || `FASE ${serv.fase}`;
|
||||
ws.getCell(`B${row}`).font = faseFont;
|
||||
fillRow(ws, row, "B", "K", PRIMARY_LIGHT);
|
||||
row++;
|
||||
}
|
||||
|
||||
const isAlt = row % 2 === 0;
|
||||
const rowBg = isAlt ? LIGHT_BG : WHITE;
|
||||
|
||||
ws.getCell(`B${row}`).value = "";
|
||||
ws.getCell(`C${row}`).value = serv.tipoPago === "unico" ? "Unico" : "Mensual";
|
||||
ws.getCell(`C${row}`).font = valueFont;
|
||||
ws.mergeCells(`D${row}:J${row}`);
|
||||
ws.getCell(`D${row}`).value = serv.nombre;
|
||||
ws.getCell(`D${row}`).font = valueFont;
|
||||
ws.getCell(`K${row}`).value = serv.precio;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = valueFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
|
||||
for (const c of cols) {
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: rowBg } };
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), BORDER_COLOR);
|
||||
}
|
||||
row++;
|
||||
}
|
||||
|
||||
row++;
|
||||
const totalUnico = serviciosUnicos.reduce((s, x) => s + x.precio, 0);
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "Total Pago Unico";
|
||||
ws.getCell(`B${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).value = totalUnico;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row++;
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "(+ IVA)";
|
||||
ws.getCell(`B${row}`).font = { ...smallFont, italic: false };
|
||||
row++;
|
||||
|
||||
const totalMensual = serviciosMensuales.reduce((s, x) => s + x.precio, 0);
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "Total Pago Mensual";
|
||||
ws.getCell(`B${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).value = totalMensual;
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = totalFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row++;
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = "(+ IVA)";
|
||||
ws.getCell(`B${row}`).font = { ...smallFont, italic: false };
|
||||
row += 2;
|
||||
|
||||
if (draft.planBucefaloNivel) {
|
||||
ws.mergeCells(`B${row}:J${row}`);
|
||||
ws.getCell(`B${row}`).value = `CRM Bucefalo - ${draft.planBucefaloNivel.charAt(0).toUpperCase() + draft.planBucefaloNivel.slice(1)}`;
|
||||
ws.getCell(`B${row}`).font = boldFont;
|
||||
ws.getCell(`K${row}`).value = bucefaloPrecio(draft.planBucefaloNivel);
|
||||
ws.getCell(`K${row}`).numFmt = '$#,##0.00';
|
||||
ws.getCell(`K${row}`).font = boldFont;
|
||||
ws.getCell(`K${row}`).alignment = { horizontal: "right" };
|
||||
for (const c of cols) {
|
||||
applyThinBorder(ws.getCell(`${c}${row}`), PRIMARY);
|
||||
ws.getCell(`${c}${row}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
}
|
||||
row += 2;
|
||||
}
|
||||
|
||||
ws.mergeCells(`B${row}:K${row}`);
|
||||
ws.getCell(`B${row}`).value = "Todos los precios son en Moneda Nacional (MX), los precios no incluyen IVA. Vigencia de 15 dias habiles.";
|
||||
ws.getCell(`B${row}`).font = smallFont;
|
||||
|
||||
for (const serv of draft.servicios) {
|
||||
const safeName = serv.nombre.substring(0, 31).replace(/[/\\*?[\]:]/g, "");
|
||||
const dw = workbook.addWorksheet(safeName);
|
||||
dw.columns = [
|
||||
{ width: 3 },
|
||||
{ width: 35 }, { width: 5 }, { width: 15 },
|
||||
{ width: 5 },
|
||||
{ width: 35 }, { width: 5 }, { width: 15 },
|
||||
{ width: 5 }, { width: 18 },
|
||||
];
|
||||
dw.views = [{ showGridLines: false }];
|
||||
|
||||
dw.mergeCells("B1:J1");
|
||||
dw.getCell("B1").value = `${fases[serv.fase] || "FASE " + serv.fase} — ${serv.nombre}`;
|
||||
dw.getCell("B1").font = { bold: true, size: 14, name: "Calibri", color: { argb: WHITE } };
|
||||
dw.getCell("B1").alignment = { vertical: "middle" };
|
||||
fillRow(dw, 1, "A", "J", PRIMARY);
|
||||
dw.getRow(1).height = 30;
|
||||
|
||||
let r = 3;
|
||||
dw.getCell(`B${r}`).value = "Cliente:";
|
||||
dw.getCell(`B${r}`).font = labelFont;
|
||||
dw.getCell(`C${r}`).value = draft.clienteEmpresa || draft.clienteNombre;
|
||||
dw.getCell(`C${r}`).font = boldFont;
|
||||
dw.getCell(`F${r}`).value = "No. Cotizacion:";
|
||||
dw.getCell(`F${r}`).font = labelFont;
|
||||
dw.getCell(`G${r}`).value = "BORRADOR";
|
||||
dw.getCell(`G${r}`).font = boldFont;
|
||||
r += 2;
|
||||
|
||||
dw.getCell(`B${r}`).value = "Servicio:";
|
||||
dw.getCell(`B${r}`).font = labelFont;
|
||||
dw.getCell(`C${r}`).value = serv.nombre;
|
||||
dw.getCell(`C${r}`).font = { ...boldFont, size: 12, color: { argb: PRIMARY } };
|
||||
dw.getCell(`F${r}`).value = "Tiempo de Entrega:";
|
||||
dw.getCell(`F${r}`).font = labelFont;
|
||||
dw.getCell(`G${r}`).value = serv.tiempoEntrega;
|
||||
dw.getCell(`G${r}`).font = valueFont;
|
||||
r += 2;
|
||||
|
||||
const thCols = ["B", "I"];
|
||||
for (const c of thCols) {
|
||||
dw.getCell(`${c}${r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY } };
|
||||
dw.getCell(`${c}${r}`).font = headerFont;
|
||||
dw.getCell(`${c}${r}`).border = { bottom: { style: "thin", color: { argb: PRIMARY } } };
|
||||
}
|
||||
dw.getCell(`B${r}`).value = "Entregable";
|
||||
dw.getCell(`I${r}`).value = "";
|
||||
r++;
|
||||
|
||||
for (let i = 0; i < serv.entregables.length; i++) {
|
||||
const isAlt = i % 2 === 1;
|
||||
dw.getCell(`B${i + r}`).value = `${i + 1}. ${serv.entregables[i]}`;
|
||||
dw.getCell(`B${i + r}`).font = valueFont;
|
||||
const bg = isAlt ? LIGHT_BG : WHITE;
|
||||
dw.getCell(`B${i + r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: bg } };
|
||||
applyThinBorder(dw.getCell(`B${i + r}`), BORDER_COLOR);
|
||||
}
|
||||
r += serv.entregables.length + 1;
|
||||
|
||||
for (const c of ["B", "I"]) {
|
||||
dw.getCell(`${c}${r}`).fill = { type: "pattern", pattern: "solid", fgColor: { argb: PRIMARY_LIGHT } };
|
||||
applyThinBorder(dw.getCell(`${c}${r}`), PRIMARY);
|
||||
}
|
||||
dw.getCell(`B${r}`).value = `Total Pago ${serv.tipoPago === "unico" ? "Unico" : "Mensual"}`;
|
||||
dw.getCell(`B${r}`).font = totalFont;
|
||||
dw.getCell(`I${r}`).value = serv.precio;
|
||||
dw.getCell(`I${r}`).numFmt = '$#,##0.00';
|
||||
dw.getCell(`I${r}`).font = totalFont;
|
||||
dw.getCell(`I${r}`).alignment = { horizontal: "right" };
|
||||
r++;
|
||||
dw.getCell(`B${r}`).value = "(+ IVA)";
|
||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
||||
r += 2;
|
||||
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = "Esta cotizacion tiene una vigencia de 15 dias habiles. Todos los precios en MXN, precios + IVA.";
|
||||
dw.getCell(`B${r}`).font = smallFont;
|
||||
r += 2;
|
||||
|
||||
dw.getCell(`B${r}`).value = bancaria.razon_social || "Cotizador E3";
|
||||
dw.getCell(`B${r}`).font = { ...boldFont, color: { argb: PRIMARY } };
|
||||
if (bancaria.domicilio_fiscal) {
|
||||
r++;
|
||||
dw.mergeCells(`B${r}:J${r}`);
|
||||
dw.getCell(`B${r}`).value = bancaria.domicilio_fiscal;
|
||||
dw.getCell(`B${r}`).font = { ...smallFont, italic: false };
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename="${sanitizeFilename(empresa)} - ${sanitizeFilename(draft.clienteNombre)} - BORRADOR.xlsx"`,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error("Error exporting Excel:", error);
|
||||
const message = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
||||
import { getConfigBranding, getConfigBancaria } from "@/lib/config-helpers";
|
||||
import { sanitizeFilename } from "@/lib/calculators";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const cot = await prisma.cotizacion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
cliente: true,
|
||||
asesor: true,
|
||||
servicios: { include: { servicioCatalogo: true } },
|
||||
planBucefalo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!cot) {
|
||||
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
|
||||
}
|
||||
|
||||
const config = await getConfigBancaria();
|
||||
|
||||
const branding = await getConfigBranding();
|
||||
const empresa = cot.cliente.empresa || cot.cliente.nombre;
|
||||
const nombre = `${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}`;
|
||||
|
||||
const buffer = await generateCotizacionPDF({
|
||||
numero: cot.numero,
|
||||
clienteNombre: cot.cliente.nombre,
|
||||
clienteEmpresa: cot.cliente.empresa || "",
|
||||
asesorNombre: cot.asesor.name,
|
||||
fecha: cot.fecha,
|
||||
vigencia: cot.vigencia,
|
||||
moneda: cot.moneda,
|
||||
tipoCambio: cot.tipoCambio,
|
||||
proyecto: cot.proyecto,
|
||||
esquemaPago: cot.esquemaPago,
|
||||
servicios: cot.servicios.filter((s) => s.seleccionado).map((s) => ({
|
||||
nombre: s.servicioCatalogo?.nombre || "Servicio",
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precio,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
|
||||
})),
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
|
||||
incluirBonos: cot.incluirBonos,
|
||||
configBancaria: config,
|
||||
...branding,
|
||||
});
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="${nombre}.pdf"`,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { generateCotizacionPDF } from "@/lib/pdf-generator";
|
||||
import { calcularVigencia, bucefaloPrecio, sanitizeFilename } from "@/lib/calculators";
|
||||
import { getConfigBranding } from "@/lib/config-helpers";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { draft } = body as {
|
||||
draft: {
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
asesorNombre: string;
|
||||
fecha: string;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
incluirBonos: boolean;
|
||||
servicios: {
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
}[];
|
||||
planBucefaloNivel: string | null;
|
||||
observaciones: string;
|
||||
};
|
||||
};
|
||||
|
||||
const fechaCot = new Date(draft.fecha);
|
||||
const vigencia = calcularVigencia(fechaCot);
|
||||
|
||||
const branding = await getConfigBranding();
|
||||
const empresa = draft.clienteEmpresa || draft.clienteNombre;
|
||||
const nombre = `${sanitizeFilename(empresa)} - ${sanitizeFilename(draft.clienteNombre)} - BORRADOR`;
|
||||
|
||||
const buffer = await generateCotizacionPDF({
|
||||
numero: "BORRADOR",
|
||||
clienteNombre: draft.clienteNombre,
|
||||
clienteEmpresa: draft.clienteEmpresa,
|
||||
asesorNombre: draft.asesorNombre,
|
||||
fecha: fechaCot,
|
||||
vigencia,
|
||||
moneda: draft.moneda,
|
||||
tipoCambio: draft.tipoCambio,
|
||||
proyecto: draft.proyecto,
|
||||
esquemaPago: draft.esquemaPago,
|
||||
servicios: draft.servicios,
|
||||
planBucefaloNivel: draft.planBucefaloNivel,
|
||||
planBucefaloPrecio: draft.planBucefaloNivel ? bucefaloPrecio(draft.planBucefaloNivel) : 0,
|
||||
incluirBonos: draft.incluirBonos,
|
||||
...branding,
|
||||
});
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="${nombre}.pdf"`,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
interface ParsedRow {
|
||||
nombre: string;
|
||||
categoria: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
variante: string | null;
|
||||
}
|
||||
|
||||
const FASES_MAP: Record<string, number> = {
|
||||
auditoria: 0,
|
||||
"setup e infraestructura": 1,
|
||||
setup: 1,
|
||||
infraestructura: 1,
|
||||
"publicidad y manejo": 2,
|
||||
publicidad: 2,
|
||||
manejo: 2,
|
||||
"contenido y seo": 3,
|
||||
contenido: 3,
|
||||
seo: 3,
|
||||
};
|
||||
|
||||
function parseCsvLine(line: string): string[] {
|
||||
const fields: string[] = [];
|
||||
let current = "";
|
||||
let inQuotes = false;
|
||||
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"' && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i++;
|
||||
} else if (ch === '"') {
|
||||
inQuotes = false;
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
} else {
|
||||
if (ch === '"') {
|
||||
inQuotes = true;
|
||||
} else if (ch === ",") {
|
||||
fields.push(current.trim());
|
||||
current = "";
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
}
|
||||
fields.push(current.trim());
|
||||
return fields;
|
||||
}
|
||||
|
||||
function parseRow(fields: string[]): ParsedRow | null {
|
||||
const [nombre, categoria, faseStr, tipoPago, precioStr, tiempoEntrega, entregablesStr, variante] = fields;
|
||||
|
||||
if (!nombre || !categoria || !tipoPago || !precioStr) return null;
|
||||
|
||||
const faseKey = faseStr.toLowerCase().trim();
|
||||
const fase = FASES_MAP[faseKey];
|
||||
if (fase === undefined) return null;
|
||||
|
||||
const tipo = tipoPago.toLowerCase().trim();
|
||||
if (tipo !== "unico" && tipo !== "mensual") return null;
|
||||
|
||||
const precioBase = parseFloat(precioStr);
|
||||
if (isNaN(precioBase) || precioBase < 0) return null;
|
||||
|
||||
return {
|
||||
nombre,
|
||||
categoria,
|
||||
fase,
|
||||
tipoPago: tipo,
|
||||
precioBase,
|
||||
tiempoEntrega: tiempoEntrega || "7 - 14 dias",
|
||||
entregables: entregablesStr
|
||||
? entregablesStr.split("|").map((e) => e.trim()).filter(Boolean)
|
||||
: [],
|
||||
variante: variante || null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: "No se recibio archivo" }, { status: 400 });
|
||||
}
|
||||
|
||||
const text = await file.text();
|
||||
const lines = text
|
||||
.split(/\r?\n/)
|
||||
.filter((l) => l.trim() && !l.trim().startsWith('"CATEGORIAS') && !l.trim().startsWith('"FASES') && !l.trim().startsWith('"TIPOS') && !l.trim().startsWith('"ENTREGABLES') && !l.trim().startsWith('"VARIANTE'));
|
||||
|
||||
if (lines.length < 2) {
|
||||
return NextResponse.json({ error: "El CSV esta vacio o no tiene datos" }, { status: 400 });
|
||||
}
|
||||
|
||||
const categorias = await prisma.categoria.findMany({
|
||||
where: { activo: true },
|
||||
select: { id: true, nombre: true },
|
||||
});
|
||||
const catMap = new Map(categorias.map((c) => [c.nombre.toLowerCase(), c.id]));
|
||||
|
||||
const rows: ParsedRow[] = [];
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
const fields = parseCsvLine(lines[i]);
|
||||
if (fields.length < 5) continue;
|
||||
const row = parseRow(fields);
|
||||
if (row) rows.push(row);
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "No se encontraron filas validas. Verifica el formato del CSV." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
let creados = 0;
|
||||
let omitidos = 0;
|
||||
const errores: string[] = [];
|
||||
|
||||
const maxOrden = await prisma.servicioCatalogo.aggregate({ _max: { orden: true } });
|
||||
let nextOrden = (maxOrden._max.orden || 0) + 1;
|
||||
|
||||
const toCreate: { nombre: string; fase: number; tipoPago: string; precioBase: number; tiempoEntrega: string; entregablesDefault: string[]; variante: string | null; categoriaId: string; orden: number; activo: boolean }[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const categoriaId = catMap.get(row.categoria.toLowerCase());
|
||||
if (!categoriaId) {
|
||||
errores.push(`"${row.nombre}": categoria "${row.categoria}" no encontrada`);
|
||||
omitidos++;
|
||||
continue;
|
||||
}
|
||||
|
||||
toCreate.push({
|
||||
nombre: row.nombre,
|
||||
fase: row.fase,
|
||||
tipoPago: row.tipoPago,
|
||||
precioBase: row.precioBase,
|
||||
tiempoEntrega: row.tiempoEntrega,
|
||||
entregablesDefault: row.entregables,
|
||||
variante: row.variante,
|
||||
categoriaId,
|
||||
orden: nextOrden++,
|
||||
activo: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (toCreate.length > 0) {
|
||||
await prisma.servicioCatalogo.createMany({ data: toCreate });
|
||||
}
|
||||
creados = toCreate.length;
|
||||
|
||||
return NextResponse.json({
|
||||
creados,
|
||||
omitidos,
|
||||
errores: errores.length > 0 ? errores : undefined,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id: paqueteId } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
if (body.action === "addFase") {
|
||||
const fase = await prisma.fasePaquete.create({
|
||||
data: {
|
||||
paqueteId,
|
||||
nombre: body.nombre,
|
||||
orden: body.orden ?? 0,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(fase, { status: 201 });
|
||||
}
|
||||
|
||||
if (body.action === "updateFase") {
|
||||
const fase = await prisma.fasePaquete.update({
|
||||
where: { id: body.faseId },
|
||||
data: { nombre: body.nombre, orden: body.orden },
|
||||
});
|
||||
return NextResponse.json(fase);
|
||||
}
|
||||
|
||||
if (body.action === "deleteFase") {
|
||||
await prisma.fasePaquete.delete({ where: { id: body.faseId } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
if (body.action === "addServicio") {
|
||||
const link = await prisma.servicioPaquete.create({
|
||||
data: {
|
||||
servicioCatalogoId: body.servicioCatalogoId,
|
||||
fasePaqueteId: body.fasePaqueteId,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(link, { status: 201 });
|
||||
}
|
||||
|
||||
if (body.action === "removeServicio") {
|
||||
await prisma.servicioPaquete.deleteMany({
|
||||
where: {
|
||||
servicioCatalogoId: body.servicioCatalogoId,
|
||||
fasePaqueteId: body.fasePaqueteId,
|
||||
},
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Accion desconocida" }, { status: 400 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const paquete = await prisma.paquete.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
fases: {
|
||||
orderBy: { orden: "asc" },
|
||||
include: {
|
||||
servicios: {
|
||||
include: { servicio: { include: { categoriaRel: true } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!paquete) return NextResponse.json({ error: "No encontrado" }, { status: 404 });
|
||||
return NextResponse.json(paquete);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
const paquete = await prisma.paquete.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
activo: body.activo !== false,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(paquete);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
await prisma.paquete.delete({ where: { id } });
|
||||
return NextResponse.json({ ok: true });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const paquetes = await prisma.paquete.findMany({
|
||||
where: { activo: true },
|
||||
include: {
|
||||
fases: {
|
||||
orderBy: { orden: "asc" },
|
||||
include: {
|
||||
servicios: {
|
||||
include: { servicio: { include: { categoriaRel: true } } },
|
||||
orderBy: { servicio: { orden: "asc" } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: "asc" },
|
||||
});
|
||||
return NextResponse.json(paquetes);
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const paquete = await prisma.paquete.create({
|
||||
data: {
|
||||
nombre: body.nombre,
|
||||
descripcion: body.descripcion || null,
|
||||
fases: {
|
||||
create: (body.fases || []).map((f: { nombre: string; orden: number }, i: number) => ({
|
||||
nombre: f.nombre,
|
||||
orden: f.orden ?? i,
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: { fases: true },
|
||||
});
|
||||
return NextResponse.json(paquete, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const msg = error instanceof Error ? error.message : "Error interno";
|
||||
return NextResponse.json({ error: msg }, { status: 500 });
|
||||
}
|
||||
}
|
||||
+35
-10
@@ -1,26 +1,51 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
--background: #f8fafc;
|
||||
--foreground: #1e293b;
|
||||
--primary: #2563eb;
|
||||
--primary-dark: #1d4ed8;
|
||||
--primary-light: #dbeafe;
|
||||
--secondary: #7c3aed;
|
||||
--accent: #06b6d4;
|
||||
--success: #10b981;
|
||||
--warning: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
--sidebar-bg: #1e293b;
|
||||
--sidebar-text: #cbd5e1;
|
||||
--sidebar-active: #2563eb;
|
||||
--card-bg: #ffffff;
|
||||
--border: #e2e8f0;
|
||||
--muted: #94a3b8;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-dark: var(--primary-dark);
|
||||
--color-primary-light: var(--primary-light);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-accent: var(--accent);
|
||||
--color-success: var(--success);
|
||||
--color-warning: var(--warning);
|
||||
--color-danger: var(--danger);
|
||||
--color-sidebar-bg: var(--sidebar-bg);
|
||||
--color-sidebar-text: var(--sidebar-text);
|
||||
--color-card-bg: var(--card-bg);
|
||||
--color-border: var(--border);
|
||||
--color-muted: var(--muted);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-family: var(--font-sans), Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #cbd5e1 transparent;
|
||||
}
|
||||
|
||||
+5
-3
@@ -13,8 +13,9 @@ const geistMono = Geist_Mono({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "Cotizador - Uriel Jareth Consulting",
|
||||
description:
|
||||
"Sistema de generacion de cotizaciones para Uriel Jareth Consulting",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -24,7 +25,8 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
lang="es"
|
||||
suppressHydrationWarning
|
||||
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else {
|
||||
const data = await res.json();
|
||||
setError(data.error || "Error al iniciar sesion");
|
||||
}
|
||||
} catch {
|
||||
setError("Error de conexion");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="bg-white rounded-xl shadow-lg border border-border p-8">
|
||||
<h1 className="text-2xl font-bold text-center mb-2">Cotizador</h1>
|
||||
<p className="text-center text-muted text-sm mb-6">
|
||||
Uriel Jareth Consulting
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-3 mb-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="[email protected]"
|
||||
suppressHydrationWarning
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
placeholder="Tu contrasena"
|
||||
suppressHydrationWarning
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
suppressHydrationWarning
|
||||
className="w-full py-2.5 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 transition-colors"
|
||||
>
|
||||
{loading ? "Ingresando..." : "Ingresar"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import Image from "next/image";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
</h1>
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Save,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Check,
|
||||
Gift,
|
||||
DollarSign,
|
||||
User,
|
||||
Building,
|
||||
Mail,
|
||||
Phone,
|
||||
Package,
|
||||
} from "lucide-react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
formatCurrency,
|
||||
IVA_RATE,
|
||||
PLANES_BUCEFALO as PLANES,
|
||||
FASES as FASES_LABELS,
|
||||
calcularVigencia,
|
||||
generarNumeroCotizacion,
|
||||
bucefaloPrecio,
|
||||
} from "@/lib/calculators";
|
||||
import {
|
||||
useCotizacionStore,
|
||||
ServicioSeleccionado,
|
||||
} from "@/lib/store";
|
||||
import {
|
||||
ExportPDFButtonDraft,
|
||||
ExportExcelButtonDraft,
|
||||
} from "@/components/ExportButtons";
|
||||
|
||||
export interface ServicioCatalogo {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: string[];
|
||||
categoriaNombre: string;
|
||||
variante: string | null;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
export interface Asesor {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface ExistingData {
|
||||
id: string;
|
||||
numero: string;
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
clienteEmail: string;
|
||||
clienteTelefono: string;
|
||||
asesorId: string;
|
||||
asesorNombre: string;
|
||||
fecha: Date;
|
||||
vigencia: Date;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
incluirBonos: boolean;
|
||||
incluirFinanciamiento: boolean;
|
||||
observaciones: string;
|
||||
planBucefaloNivel: string | null;
|
||||
estado: string;
|
||||
servicios: ServicioSeleccionado[];
|
||||
}
|
||||
|
||||
export interface PaqueteServicio {
|
||||
id: string;
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: string[];
|
||||
}
|
||||
|
||||
export interface PaqueteFase {
|
||||
nombre: string;
|
||||
orden: number;
|
||||
servicios: PaqueteServicio[];
|
||||
}
|
||||
|
||||
export interface PaquetePreview {
|
||||
id: string;
|
||||
nombre: string;
|
||||
fases: PaqueteFase[];
|
||||
}
|
||||
|
||||
export interface CotizacionFormProps {
|
||||
mode: "new" | "edit";
|
||||
servicios: ServicioCatalogo[];
|
||||
asesores: Asesor[];
|
||||
nextSeq?: number;
|
||||
existingData?: ExistingData;
|
||||
paquetes?: PaquetePreview[];
|
||||
}
|
||||
|
||||
const FASES = FASES_LABELS;
|
||||
|
||||
const INPUT_CLS =
|
||||
"w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary";
|
||||
const BTN_PRIMARY =
|
||||
"flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 disabled:cursor-not-allowed transition-colors";
|
||||
|
||||
export function CotizacionForm({
|
||||
mode,
|
||||
servicios,
|
||||
asesores,
|
||||
nextSeq,
|
||||
existingData,
|
||||
paquetes,
|
||||
}: CotizacionFormProps) {
|
||||
const router = useRouter();
|
||||
const store = useCotizacionStore();
|
||||
|
||||
const [expandedFases, setExpandedFases] = useState<Set<number>>(
|
||||
new Set([0, 1, 2, 3])
|
||||
);
|
||||
const [expandedServicios, setExpandedServicios] = useState<Set<string>>(
|
||||
new Set()
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedPaquete, setSelectedPaquete] = useState<string>("");
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "edit" && existingData) {
|
||||
store.setField("clienteNombre", existingData.clienteNombre);
|
||||
store.setField("clienteEmpresa", existingData.clienteEmpresa);
|
||||
store.setField("clienteEmail", existingData.clienteEmail);
|
||||
store.setField("clienteTelefono", existingData.clienteTelefono);
|
||||
store.setField("asesorId", existingData.asesorId);
|
||||
store.setField("asesorNombre", existingData.asesorNombre);
|
||||
store.setField("fecha", new Date(existingData.fecha));
|
||||
store.setField("vigencia", new Date(existingData.vigencia));
|
||||
store.setField("moneda", existingData.moneda);
|
||||
store.setField("tipoCambio", existingData.tipoCambio);
|
||||
store.setField("proyecto", existingData.proyecto);
|
||||
store.setField("esquemaPago", existingData.esquemaPago);
|
||||
store.setField("incluirBonos", existingData.incluirBonos);
|
||||
store.setField("incluirFinanciamiento", existingData.incluirFinanciamiento);
|
||||
store.setField("observaciones", existingData.observaciones);
|
||||
store.setField("planBucefaloNivel", existingData.planBucefaloNivel);
|
||||
store.setServicios(existingData.servicios);
|
||||
}
|
||||
}, [mode, existingData]);
|
||||
|
||||
const selectedIds = new Set(store.draft.servicios.map((s) => s.catalogoId));
|
||||
|
||||
const toggleFase = (fase: number) => {
|
||||
setExpandedFases((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(fase)) next.delete(fase);
|
||||
else next.add(fase);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleServicioExpand = (id: string) => {
|
||||
setExpandedServicios((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleToggleServicio = (serv: ServicioCatalogo) => {
|
||||
if (selectedIds.has(serv.id)) {
|
||||
store.removeServicio(serv.id);
|
||||
} else {
|
||||
store.toggleServicio({
|
||||
catalogoId: serv.id,
|
||||
nombre: serv.nombre,
|
||||
fase: serv.fase,
|
||||
tipoPago: serv.tipoPago,
|
||||
precio: serv.precioBase,
|
||||
tiempoEntrega: serv.tiempoEntrega,
|
||||
entregables: serv.entregablesDefault,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrecioChange = (catalogoId: string, precio: number) => {
|
||||
store.updateServicio(catalogoId, { precio });
|
||||
};
|
||||
|
||||
const buildRequestBody = () => ({
|
||||
...(mode === "new" && {
|
||||
numero: generarNumeroCotizacion(
|
||||
(asesores.find((a) => a.id === store.draft.asesorId)?.name || "XX")
|
||||
.substring(0, 2)
|
||||
.toUpperCase(),
|
||||
nextSeq || 1
|
||||
),
|
||||
asesorId: store.draft.asesorId,
|
||||
}),
|
||||
fecha: store.draft.fecha,
|
||||
vigencia:
|
||||
store.draft.vigencia ||
|
||||
calcularVigencia(new Date(store.draft.fecha)),
|
||||
moneda: store.draft.moneda,
|
||||
tipoCambio: store.draft.tipoCambio,
|
||||
proyecto: store.draft.proyecto,
|
||||
esquemaPago: store.draft.esquemaPago,
|
||||
incluirBonos: store.draft.incluirBonos,
|
||||
incluirFinanciamiento: store.draft.incluirFinanciamiento,
|
||||
observaciones: store.draft.observaciones,
|
||||
cliente: {
|
||||
nombre: store.draft.clienteNombre,
|
||||
empresa: store.draft.clienteEmpresa,
|
||||
email: store.draft.clienteEmail,
|
||||
telefono: store.draft.clienteTelefono,
|
||||
},
|
||||
servicios: store.draft.servicios,
|
||||
planBucefalo: store.draft.planBucefaloNivel
|
||||
? {
|
||||
nivel: store.draft.planBucefaloNivel,
|
||||
precio: bucefaloPrecio(store.draft.planBucefaloNivel),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const url =
|
||||
mode === "edit" && existingData
|
||||
? `/api/cotizaciones/${existingData.id}`
|
||||
: "/api/cotizaciones";
|
||||
const method = mode === "edit" ? "PUT" : "POST";
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(buildRequestBody()),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
if (mode === "new") {
|
||||
const data = await res.json();
|
||||
router.push(`/cotizaciones/${data.id}`);
|
||||
} else {
|
||||
router.push(`/cotizaciones/${existingData!.id}`);
|
||||
}
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert("Error: " + (err.error || "No se pudo guardar"));
|
||||
}
|
||||
} catch {
|
||||
alert("Error al guardar la cotizacion");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const totalUnico = store.draft.servicios
|
||||
.filter((s) => s.tipoPago === "unico")
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
const totalMensual = store.draft.servicios
|
||||
.filter((s) => s.tipoPago === "mensual")
|
||||
.reduce((sum, s) => sum + s.precio, 0);
|
||||
const ivaUnico = totalUnico * IVA_RATE;
|
||||
const ivaMensual = totalMensual * IVA_RATE;
|
||||
|
||||
const fases = [0, 1, 2, 3];
|
||||
const serviciosPorFase = fases.reduce(
|
||||
(acc, fase) => {
|
||||
acc[fase] = servicios.filter((s) => s.fase === fase);
|
||||
return acc;
|
||||
},
|
||||
{} as Record<number, ServicioCatalogo[]>
|
||||
);
|
||||
|
||||
const title =
|
||||
mode === "edit" && existingData
|
||||
? `Editar ${existingData.numero}`
|
||||
: "Nueva Cotizacion";
|
||||
const canSave =
|
||||
!saving &&
|
||||
!!store.draft.clienteNombre &&
|
||||
(mode === "edit" || !!store.draft.asesorId);
|
||||
|
||||
return (
|
||||
<div className="flex gap-6">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{title}</h1>
|
||||
{mode === "edit" && (
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Modifica los servicios y datos
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExportPDFButtonDraft draft={store.draft} />
|
||||
<ExportExcelButtonDraft draft={store.draft} />
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={!canSave}
|
||||
className={BTN_PRIMARY}
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
{saving
|
||||
? "Guardando..."
|
||||
: mode === "edit"
|
||||
? "Guardar Cambios"
|
||||
: "Guardar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Datos Generales</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
<User className="w-3.5 h-3.5 inline mr-1" />
|
||||
Cliente *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={store.draft.clienteNombre}
|
||||
onChange={(e) =>
|
||||
store.setField("clienteNombre", e.target.value)
|
||||
}
|
||||
placeholder="Nombre del cliente"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
<Building className="w-3.5 h-3.5 inline mr-1" />
|
||||
Empresa
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={store.draft.clienteEmpresa}
|
||||
onChange={(e) =>
|
||||
store.setField("clienteEmpresa", e.target.value)
|
||||
}
|
||||
placeholder="Nombre de la empresa"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
<Mail className="w-3.5 h-3.5 inline mr-1" />
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={store.draft.clienteEmail}
|
||||
onChange={(e) =>
|
||||
store.setField("clienteEmail", e.target.value)
|
||||
}
|
||||
placeholder="[email protected]"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
<Phone className="w-3.5 h-3.5 inline mr-1" />
|
||||
Telefono
|
||||
</label>
|
||||
<input
|
||||
type="tel"
|
||||
value={store.draft.clienteTelefono}
|
||||
onChange={(e) =>
|
||||
store.setField("clienteTelefono", e.target.value)
|
||||
}
|
||||
placeholder="+52 614 123 4567"
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Asesor Comercial *
|
||||
</label>
|
||||
<select
|
||||
value={store.draft.asesorId}
|
||||
onChange={(e) => {
|
||||
const a = asesores.find((x) => x.id === e.target.value);
|
||||
store.setField("asesorId", e.target.value);
|
||||
if (a) store.setField("asesorNombre", a.name);
|
||||
}}
|
||||
className={INPUT_CLS}
|
||||
>
|
||||
<option value="">Seleccionar asesor</option>
|
||||
{asesores.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Moneda
|
||||
</label>
|
||||
<select
|
||||
value={store.draft.moneda}
|
||||
onChange={(e) => store.setField("moneda", e.target.value)}
|
||||
className={INPUT_CLS}
|
||||
>
|
||||
<option value="MXN">MXN</option>
|
||||
<option value="USD">USD</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Tipo de Cambio
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={store.draft.tipoCambio}
|
||||
onChange={(e) =>
|
||||
store.setField("tipoCambio", e.target.value)
|
||||
}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Esquema de Pagos
|
||||
</label>
|
||||
<select
|
||||
value={store.draft.esquemaPago}
|
||||
onChange={(e) =>
|
||||
store.setField("esquemaPago", e.target.value)
|
||||
}
|
||||
className={INPUT_CLS}
|
||||
>
|
||||
<option value="Pago Unico">Pago Unico</option>
|
||||
<option value="Mensual">Mensual</option>
|
||||
<option value="Pago Unico/Mensual">Pago Unico/Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mode === "new" && paquetes && paquetes.length > 0 && (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h2 className="font-semibold text-lg mb-3">
|
||||
Iniciar desde Paquete
|
||||
</h2>
|
||||
<div className="flex items-center gap-3">
|
||||
<select
|
||||
value={selectedPaquete}
|
||||
onChange={(e) => setSelectedPaquete(e.target.value)}
|
||||
className={`flex-1 ${INPUT_CLS} bg-white`}
|
||||
>
|
||||
<option value="">Seleccionar paquete...</option>
|
||||
{paquetes.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.nombre} (
|
||||
{p.fases.reduce(
|
||||
(sum, f) => sum + f.servicios.length,
|
||||
0
|
||||
)}{" "}
|
||||
servicios)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => {
|
||||
const pk = paquetes.find(
|
||||
(p) => p.id === selectedPaquete
|
||||
);
|
||||
if (!pk) return;
|
||||
const allServs: ServicioSeleccionado[] = [];
|
||||
for (const fase of pk.fases) {
|
||||
for (const s of fase.servicios) {
|
||||
if (!allServs.find((x) => x.catalogoId === s.id)) {
|
||||
allServs.push({
|
||||
catalogoId: s.id,
|
||||
nombre: s.nombre,
|
||||
fase: s.fase,
|
||||
tipoPago: s.tipoPago,
|
||||
precio: s.precioBase,
|
||||
tiempoEntrega: s.tiempoEntrega,
|
||||
entregables: s.entregablesDefault,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
store.setServicios(allServs);
|
||||
}}
|
||||
disabled={!selectedPaquete}
|
||||
className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Package className="w-4 h-4" />
|
||||
Cargar servicios
|
||||
</button>
|
||||
{store.draft.servicios.length > 0 && (
|
||||
<button
|
||||
onClick={() => {
|
||||
store.setServicios([]);
|
||||
setSelectedPaquete("");
|
||||
}}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 text-muted"
|
||||
>
|
||||
Limpiar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fases.map((fase) => {
|
||||
const serviciosFase = serviciosPorFase[fase];
|
||||
if (!serviciosFase?.length) return null;
|
||||
const isExpanded = expandedFases.has(fase);
|
||||
return (
|
||||
<div
|
||||
key={fase}
|
||||
className="bg-card-bg rounded-xl border border-border mb-4"
|
||||
>
|
||||
<button
|
||||
onClick={() => toggleFase(fase)}
|
||||
className="w-full flex items-center gap-3 px-5 py-4 text-left"
|
||||
>
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-muted" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-muted" />
|
||||
)}
|
||||
<h3 className="font-semibold">{FASES[fase]}</h3>
|
||||
<span className="text-xs text-muted ml-auto">
|
||||
{
|
||||
serviciosFase.filter((s) => selectedIds.has(s.id))
|
||||
.length
|
||||
}
|
||||
/{serviciosFase.length} seleccionados
|
||||
</span>
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="px-5 pb-4 space-y-2">
|
||||
{serviciosFase.map((serv) => {
|
||||
const isSelected = selectedIds.has(serv.id);
|
||||
const isExpandedServ = expandedServicios.has(
|
||||
serv.id
|
||||
);
|
||||
const servicioData = store.draft.servicios.find(
|
||||
(s) => s.catalogoId === serv.id
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={serv.id}
|
||||
className={clsx(
|
||||
"border rounded-lg transition-colors",
|
||||
isSelected
|
||||
? "border-primary bg-primary-light/30"
|
||||
: "border-border"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3 px-4 py-3">
|
||||
<button
|
||||
onClick={() => handleToggleServicio(serv)}
|
||||
className={clsx(
|
||||
"w-5 h-5 rounded border flex items-center justify-center shrink-0 transition-colors",
|
||||
isSelected
|
||||
? "bg-primary border-primary text-white"
|
||||
: "border-gray-300 hover:border-primary"
|
||||
)}
|
||||
>
|
||||
{isSelected && (
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-sm truncate">
|
||||
{serv.nombre}
|
||||
</span>
|
||||
<span className="text-xs px-1.5 py-0.5 bg-gray-100 rounded text-muted">
|
||||
{serv.categoriaNombre}
|
||||
</span>
|
||||
{serv.variante && (
|
||||
<span className="text-xs px-1.5 py-0.5 bg-purple-100 rounded text-purple-700">
|
||||
{serv.variante}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs text-muted">
|
||||
<span>
|
||||
{serv.tipoPago === "unico"
|
||||
? "Pago Unico"
|
||||
: "Mensual"}
|
||||
</span>
|
||||
<span>{serv.tiempoEntrega}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{isSelected && (
|
||||
<div className="flex items-center gap-1">
|
||||
<DollarSign className="w-3.5 h-3.5 text-muted" />
|
||||
<input
|
||||
type="number"
|
||||
value={
|
||||
servicioData?.precio ||
|
||||
serv.precioBase
|
||||
}
|
||||
onChange={(e) =>
|
||||
handlePrecioChange(
|
||||
serv.id,
|
||||
parseFloat(e.target.value) ||
|
||||
0
|
||||
)
|
||||
}
|
||||
className="w-24 px-2 py-1 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={() =>
|
||||
toggleServicioExpand(serv.id)
|
||||
}
|
||||
className="text-xs text-muted hover:text-primary px-2 py-1"
|
||||
>
|
||||
{isExpandedServ ? "Ocultar" : "Ver"}
|
||||
</button>
|
||||
</div>
|
||||
<span className="font-semibold text-sm w-24 text-right shrink-0">
|
||||
{formatCurrency(
|
||||
servicioData?.precio || serv.precioBase
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{isExpandedServ && (
|
||||
<div className="px-4 pb-3 border-t border-border/50 mt-1 pt-3">
|
||||
<p className="text-xs text-muted mb-2">
|
||||
Entregables:
|
||||
</p>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-1">
|
||||
{(
|
||||
servicioData?.entregables ||
|
||||
serv.entregablesDefault
|
||||
).map((ent, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-start gap-2 text-xs"
|
||||
>
|
||||
<Check className="w-3 h-3 text-success mt-0.5 shrink-0" />
|
||||
<span>{ent}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-4">
|
||||
<h3 className="font-semibold mb-3">
|
||||
Plan Bucefalo CRM (Opcional)
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{PLANES.map((plan) => (
|
||||
<button
|
||||
key={plan.nivel}
|
||||
onClick={() => {
|
||||
if (
|
||||
store.draft.planBucefaloNivel === plan.nivel
|
||||
) {
|
||||
store.removeServicio(
|
||||
"bucefalo-" + plan.nivel
|
||||
);
|
||||
store.setField("planBucefaloNivel", null);
|
||||
} else {
|
||||
store.setField(
|
||||
"planBucefaloNivel",
|
||||
plan.nivel
|
||||
);
|
||||
store.removeServicio(
|
||||
"bucefalo-" + plan.nivel
|
||||
);
|
||||
store.toggleServicio({
|
||||
catalogoId: "bucefalo-" + plan.nivel,
|
||||
nombre: `Plan Bucefalo ${plan.label}`,
|
||||
fase: 2,
|
||||
tipoPago: "mensual",
|
||||
precio: plan.precio,
|
||||
tiempoEntrega: "Mensual",
|
||||
entregables: [
|
||||
"CRM completo segun plan contratado",
|
||||
],
|
||||
});
|
||||
}
|
||||
}}
|
||||
className={clsx(
|
||||
"border rounded-lg p-3 text-center transition-colors",
|
||||
store.draft.planBucefaloNivel === plan.nivel
|
||||
? "border-primary bg-primary-light/30"
|
||||
: "border-border hover:border-primary/50"
|
||||
)}
|
||||
>
|
||||
<div className="font-medium text-sm">
|
||||
{plan.label}
|
||||
</div>
|
||||
<div className="text-lg font-bold mt-1">
|
||||
{formatCurrency(plan.precio)}
|
||||
</div>
|
||||
<div className="text-xs text-muted">/mes</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-4">
|
||||
<div className="flex items-center gap-6">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={store.draft.incluirBonos}
|
||||
onChange={(e) =>
|
||||
store.setField("incluirBonos", e.target.checked)
|
||||
}
|
||||
className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
|
||||
/>
|
||||
<Gift className="w-4 h-4 text-warning" />
|
||||
<span className="text-sm font-medium">
|
||||
Incluir Bonos (pago en exhibicion)
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={store.draft.incluirFinanciamiento}
|
||||
onChange={(e) =>
|
||||
store.setField(
|
||||
"incluirFinanciamiento",
|
||||
e.target.checked
|
||||
)
|
||||
}
|
||||
className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
|
||||
/>
|
||||
<span className="text-sm font-medium">
|
||||
Incluir financiamiento Openpay
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5">
|
||||
<label className="block text-sm font-medium text-muted mb-1">
|
||||
Observaciones
|
||||
</label>
|
||||
<textarea
|
||||
value={store.draft.observaciones}
|
||||
onChange={(e) =>
|
||||
store.setField("observaciones", e.target.value)
|
||||
}
|
||||
rows={3}
|
||||
placeholder="Notas adicionales para la cotizacion..."
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="hidden lg:block w-80 shrink-0">
|
||||
<div className="sticky top-8">
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<div className="px-5 py-4 border-b border-border bg-gray-50">
|
||||
<h3 className="font-semibold">Resumen</h3>
|
||||
</div>
|
||||
<div className="p-5 space-y-4">
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-muted uppercase tracking-wide mb-2">
|
||||
Pago Unico
|
||||
</h4>
|
||||
{store.draft.servicios.filter(
|
||||
(s) => s.tipoPago === "unico"
|
||||
).length === 0 ? (
|
||||
<p className="text-xs text-muted">Sin servicios</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{store.draft.servicios
|
||||
.filter((s) => s.tipoPago === "unico")
|
||||
.map((s) => (
|
||||
<div
|
||||
key={s.catalogoId}
|
||||
className="flex justify-between text-xs"
|
||||
>
|
||||
<span className="truncate mr-2">
|
||||
{s.nombre}
|
||||
</span>
|
||||
<span className="shrink-0 font-medium">
|
||||
{formatCurrency(s.precio)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t border-border pt-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Subtotal unico</span>
|
||||
<span className="font-medium">
|
||||
{formatCurrency(totalUnico)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs text-muted mt-1">
|
||||
<span>IVA (16%)</span>
|
||||
<span>{formatCurrency(ivaUnico)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm font-bold mt-2 pt-2 border-t border-border">
|
||||
<span>Total Unico</span>
|
||||
<span className="text-primary">
|
||||
{formatCurrency(totalUnico + ivaUnico)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-xs font-medium text-muted uppercase tracking-wide mb-2">
|
||||
Pago Mensual
|
||||
</h4>
|
||||
{store.draft.servicios.filter(
|
||||
(s) => s.tipoPago === "mensual"
|
||||
).length === 0 ? (
|
||||
<p className="text-xs text-muted">Sin servicios</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{store.draft.servicios
|
||||
.filter((s) => s.tipoPago === "mensual")
|
||||
.map((s) => (
|
||||
<div
|
||||
key={s.catalogoId}
|
||||
className="flex justify-between text-xs"
|
||||
>
|
||||
<span className="truncate mr-2">
|
||||
{s.nombre}
|
||||
</span>
|
||||
<span className="shrink-0 font-medium">
|
||||
{formatCurrency(s.precio)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="border-t border-border pt-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Subtotal mensual</span>
|
||||
<span className="font-medium">
|
||||
{formatCurrency(totalMensual)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs text-muted mt-1">
|
||||
<span>IVA (16%)</span>
|
||||
<span>{formatCurrency(ivaMensual)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm font-bold mt-2 pt-2 border-t border-border">
|
||||
<span>Total Mensual</span>
|
||||
<span className="text-primary">
|
||||
{formatCurrency(totalMensual + ivaMensual)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-t border-border pt-3">
|
||||
<p className="text-xs text-muted">
|
||||
Todos los precios son en Moneda Nacional (MX), los
|
||||
precios no incluyen IVA
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
const COLORS: Record<string, string> = {
|
||||
borrador: "bg-gray-100 text-gray-700",
|
||||
enviada: "bg-blue-100 text-blue-700",
|
||||
aprobada: "bg-green-100 text-green-700",
|
||||
rechazada: "bg-red-100 text-red-700",
|
||||
};
|
||||
|
||||
export function EstadoBadge({ estado }: { estado: string }) {
|
||||
return (
|
||||
<span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${COLORS[estado] || COLORS.borrador}`}>
|
||||
{estado.charAt(0).toUpperCase() + estado.slice(1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
"use client";
|
||||
|
||||
import { FileDown, FileSpreadsheet, Loader2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
function getFilenameFromHeaders(headers: Headers, fallback: string): string {
|
||||
const cd = headers.get("Content-Disposition");
|
||||
if (cd) {
|
||||
const match = cd.match(/filename="?(.+?)"?$/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function useFileExport() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const download = async (url: string, fallback: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (res.ok) {
|
||||
const filename = getFilenameFromHeaders(res.headers, fallback);
|
||||
const blob = await res.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = blobUrl;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} else {
|
||||
alert("Error al exportar");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al exportar");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadPost = async (url: string, body: unknown, fallback: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (res.ok) {
|
||||
const filename = getFilenameFromHeaders(res.headers, fallback);
|
||||
const blob = await res.blob();
|
||||
const blobUrl = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = blobUrl;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(blobUrl);
|
||||
} else {
|
||||
alert("Error al exportar");
|
||||
}
|
||||
} catch {
|
||||
alert("Error al exportar");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { loading, download, downloadPost };
|
||||
}
|
||||
|
||||
export function ExportExcelButtonSaved({ cotizacionId }: { cotizacionId: string }) {
|
||||
const { loading, download } = useFileExport();
|
||||
return (
|
||||
<button
|
||||
onClick={() => download(`/api/export/excel/${cotizacionId}`, "COTIZACION.xlsx")}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileSpreadsheet className="w-4 h-4 text-green-600" />}
|
||||
Excel
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExportPDFButtonSaved({ cotizacionId }: { cotizacionId: string }) {
|
||||
const { loading, download } = useFileExport();
|
||||
return (
|
||||
<button
|
||||
onClick={() => download(`/api/export/pdf/${cotizacionId}`, "COTIZACION.pdf")}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileDown className="w-4 h-4 text-red-600" />}
|
||||
PDF
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExportExcelButtonDraft({ draft }: { draft: unknown }) {
|
||||
const { loading, downloadPost } = useFileExport();
|
||||
return (
|
||||
<button
|
||||
onClick={() => downloadPost("/api/export/excel", { draft }, "COTIZACION.xlsx")}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileSpreadsheet className="w-4 h-4 text-green-600" />}
|
||||
Excel
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function ExportPDFButtonDraft({ draft }: { draft: unknown }) {
|
||||
const { loading, downloadPost } = useFileExport();
|
||||
return (
|
||||
<button
|
||||
onClick={() => downloadPost("/api/export/pdf", { draft }, "COTIZACION.pdf")}
|
||||
disabled={loading}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileDown className="w-4 h-4 text-red-600" />}
|
||||
PDF
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
FileText,
|
||||
Database,
|
||||
Users,
|
||||
Settings,
|
||||
Menu,
|
||||
X,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
const navigation = [
|
||||
{ name: "Dashboard", href: "/", icon: LayoutDashboard },
|
||||
{ name: "Cotizaciones", href: "/cotizaciones", icon: FileText },
|
||||
{ name: "Catalogo", href: "/catalogo", icon: Database },
|
||||
{ name: "Clientes", href: "/clientes", icon: Users },
|
||||
{ name: "Configuracion", href: "/configuracion", icon: Settings },
|
||||
];
|
||||
|
||||
export default function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
|
||||
const handleLogout = async () => {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
router.push("/login");
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setMobileOpen(true)}
|
||||
className="lg:hidden fixed top-4 left-4 z-50 p-2 rounded-lg bg-sidebar-bg text-white"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{mobileOpen && (
|
||||
<div
|
||||
className="lg:hidden fixed inset-0 bg-black/50 z-40"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<aside
|
||||
className={clsx(
|
||||
"fixed top-0 left-0 h-full w-64 bg-sidebar-bg z-50 flex flex-col transition-transform lg:translate-x-0",
|
||||
mobileOpen ? "translate-x-0" : "-translate-x-full"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between px-6 py-5 border-b border-white/10">
|
||||
<div>
|
||||
<h1 className="text-white font-bold text-lg">Cotizador</h1>
|
||||
<p className="text-sidebar-text text-xs">Uriel Jareth Consulting</p>
|
||||
</div>
|
||||
<button
|
||||
className="lg:hidden text-white"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 px-3 py-4 space-y-1">
|
||||
{navigation.map((item) => {
|
||||
const isActive =
|
||||
pathname === item.href ||
|
||||
(item.href !== "/" && pathname.startsWith(item.href));
|
||||
return (
|
||||
<Link
|
||||
key={item.name}
|
||||
href={item.href}
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className={clsx(
|
||||
"flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
|
||||
isActive
|
||||
? "bg-sidebar-active text-white"
|
||||
: "text-sidebar-text hover:bg-white/10 hover:text-white"
|
||||
)}
|
||||
>
|
||||
<item.icon className="w-5 h-5 shrink-0" />
|
||||
{item.name}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="px-4 py-4 border-t border-white/10">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="flex items-center gap-3 w-full px-3 py-2.5 rounded-lg text-sm font-medium text-sidebar-text hover:bg-white/10 hover:text-white transition-colors"
|
||||
>
|
||||
<LogOut className="w-5 h-5 shrink-0" />
|
||||
Cerrar sesion
|
||||
</button>
|
||||
<p className="text-sidebar-text text-xs mt-3">
|
||||
Digitalizando Negocios para Resultados Exponenciales
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { SignJWT, jwtVerify } from "jose";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
const JWT_SECRET = new TextEncoder().encode(
|
||||
process.env.JWT_SECRET || (() => { throw new Error("JWT_SECRET env var is required"); })()
|
||||
);
|
||||
|
||||
const COOKIE_NAME = "cotizador-session";
|
||||
|
||||
export interface SessionPayload {
|
||||
userId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
export async function createSession(payload: SessionPayload): Promise<string> {
|
||||
const token = await new SignJWT(payload as unknown as Record<string, unknown>)
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setExpirationTime("7d")
|
||||
.setIssuedAt()
|
||||
.sign(JWT_SECRET);
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function verifySession(
|
||||
token: string
|
||||
): Promise<SessionPayload | null> {
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, JWT_SECRET);
|
||||
return payload as unknown as SessionPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSession(): Promise<SessionPayload | null> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get(COOKIE_NAME)?.value;
|
||||
if (!token) return null;
|
||||
return verifySession(token);
|
||||
}
|
||||
|
||||
export function setSessionCookie(token: string) {
|
||||
return {
|
||||
name: COOKIE_NAME,
|
||||
value: token,
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax" as const,
|
||||
path: "/",
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearSessionCookie() {
|
||||
return {
|
||||
name: COOKIE_NAME,
|
||||
value: "",
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax" as const,
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
export const IVA_RATE = 0.16;
|
||||
|
||||
export const FASES: Record<number, string> = {
|
||||
0: "FASE 0 - Auditoria / Acompanamiento",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
};
|
||||
|
||||
export const FASES_SHORT: Record<number, string> = {
|
||||
0: "FASE 0 - Auditoria",
|
||||
1: "FASE 1 - Setup e Infraestructura",
|
||||
2: "FASE 2 - Publicidad y Manejo",
|
||||
3: "FASE 3 - Contenido y SEO",
|
||||
};
|
||||
|
||||
export const PLANES_BUCEFALO = [
|
||||
{ nivel: "basico", label: "Basico", precio: 1000 },
|
||||
{ nivel: "estandar", label: "Estandar", precio: 3500 },
|
||||
{ nivel: "premium", label: "Premium", precio: 4500 },
|
||||
{ nivel: "empresarial", label: "Empresarial", precio: 7500 },
|
||||
] as const;
|
||||
|
||||
export const ESTADOS_COTIZACION = ["borrador", "enviada", "aprobada", "rechazada"] as const;
|
||||
export type EstadoCotizacion = (typeof ESTADOS_COTIZACION)[number];
|
||||
|
||||
export function bucefaloPrecio(nivel: string): number {
|
||||
return PLANES_BUCEFALO.find((p) => p.nivel === nivel)?.precio ?? 0;
|
||||
}
|
||||
|
||||
export function calcularVigencia(fecha: Date): Date {
|
||||
const vigencia = new Date(fecha);
|
||||
let diasHabiles = 0;
|
||||
while (diasHabiles < 15) {
|
||||
vigencia.setDate(vigencia.getDate() + 1);
|
||||
const dia = vigencia.getDay();
|
||||
if (dia !== 0 && dia !== 6) diasHabiles++;
|
||||
}
|
||||
return vigencia;
|
||||
}
|
||||
|
||||
export function calcularFinanciamiento(input: { monto: number; meses: number; tasa: number; comision: number; iva: number }) {
|
||||
const { monto, meses, tasa, comision, iva } = input;
|
||||
const comisionTotal = (monto * comision) / 100;
|
||||
const montoConComision = monto + comisionTotal;
|
||||
const pagoMensual = montoConComision * (1 + tasa) / meses;
|
||||
const ivaMensual = pagoMensual * iva;
|
||||
const totalMensual = pagoMensual + ivaMensual;
|
||||
return {
|
||||
pagoMensual: Math.round(pagoMensual * 100) / 100,
|
||||
ivaMensual: Math.round(ivaMensual * 100) / 100,
|
||||
totalMensual: Math.round(totalMensual * 100) / 100,
|
||||
comisionTotal: Math.round(comisionTotal * 100) / 100,
|
||||
granTotal: Math.round(totalMensual * meses * 100) / 100,
|
||||
};
|
||||
}
|
||||
|
||||
export function generarNumeroCotizacion(asesorIniciales: string, secuencia: number): string {
|
||||
const now = new Date();
|
||||
const yy = now.getFullYear().toString().slice(-2);
|
||||
const mm = (now.getMonth() + 1).toString().padStart(2, "0");
|
||||
const seq = secuencia.toString().padStart(3, "0");
|
||||
return `UJ${yy}${mm}${asesorIniciales}${seq}`;
|
||||
}
|
||||
|
||||
export function sanitizeFilename(name: string): string {
|
||||
return name.replace(/[^\w\s.\-]/g, "").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
export function formatCurrency(amount: number): string {
|
||||
return new Intl.NumberFormat("es-MX", {
|
||||
style: "currency",
|
||||
currency: "MXN",
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
}
|
||||
|
||||
export function formatDate(date: Date): string {
|
||||
return new Intl.DateTimeFormat("es-MX", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
}).format(date);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { prisma } from "./db";
|
||||
|
||||
export async function getConfigBranding() {
|
||||
try {
|
||||
const configs = await prisma.configuracion.findMany({
|
||||
where: { clave: { in: ["color_primario", "color_secundario", "logo_base64"] } },
|
||||
});
|
||||
const map: Record<string, string> = {};
|
||||
for (const c of configs) map[c.clave] = c.valor;
|
||||
return {
|
||||
colorPrimario: map.color_primario || undefined,
|
||||
colorSecundario: map.color_secundario || undefined,
|
||||
logoBase64: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":").slice(1).join(":") : map.logo_base64) : undefined,
|
||||
logoMime: map.logo_base64 ? (map.logo_base64.includes(":") ? map.logo_base64.split(":")[0] : "image/png") : undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getConfigBancaria() {
|
||||
try {
|
||||
const configs = await prisma.configuracion.findMany({
|
||||
where: {
|
||||
clave: {
|
||||
in: [
|
||||
"razon_social",
|
||||
"rfc",
|
||||
"domicilio_fiscal",
|
||||
"cuenta_nacional",
|
||||
"clabe_interbancaria",
|
||||
"cuenta_internacional",
|
||||
"cuenta_internacional_swift",
|
||||
"hora_centinela",
|
||||
"terminos_condiciones",
|
||||
"no_incluye",
|
||||
"notas_adicionales",
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const map: Record<string, string> = {};
|
||||
for (const c of configs) map[c.clave] = c.valor;
|
||||
return map;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { PrismaClient } from "@/generated/prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
function createPrismaClient() {
|
||||
const adapter = new PrismaPg({
|
||||
host: process.env.DB_HOST || "localhost",
|
||||
port: parseInt(process.env.DB_PORT || "5432"),
|
||||
user: process.env.DB_USER || "postgres",
|
||||
password: process.env.DB_PASSWORD || "postgres",
|
||||
database: process.env.DB_NAME || "cotizador_e3",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
@@ -0,0 +1,406 @@
|
||||
import PDFDocument from "pdfkit";
|
||||
import { FASES_SHORT as FASES } from "./calculators";
|
||||
|
||||
interface ServicioPDF {
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
}
|
||||
|
||||
interface CotizacionPDFData {
|
||||
numero: string;
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
asesorNombre: string;
|
||||
fecha: Date;
|
||||
vigencia: Date;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
servicios: ServicioPDF[];
|
||||
planBucefaloNivel: string | null;
|
||||
planBucefaloPrecio: number;
|
||||
incluirBonos: boolean;
|
||||
configBancaria?: Record<string, string>;
|
||||
colorPrimario?: string;
|
||||
colorSecundario?: string;
|
||||
logoBase64?: string;
|
||||
logoMime?: string;
|
||||
}
|
||||
|
||||
function fmt(n: number): string {
|
||||
return new Intl.NumberFormat("es-MX", {
|
||||
style: "currency",
|
||||
currency: "MXN",
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(n);
|
||||
}
|
||||
|
||||
function fmtDate(d: Date): string {
|
||||
return new Intl.DateTimeFormat("es-MX", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
}).format(d);
|
||||
}
|
||||
|
||||
async function toPngBuffer(base64: string, mime: string): Promise<Buffer> {
|
||||
const buf = Buffer.from(base64, "base64");
|
||||
if (mime === "image/svg+xml") {
|
||||
const sharp = (await import("sharp")).default;
|
||||
return sharp(buf).png().toBuffer();
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Buffer> {
|
||||
const logoBuffer = data.logoBase64 && data.logoMime
|
||||
? await toPngBuffer(data.logoBase64, data.logoMime).catch(() => undefined)
|
||||
: data.logoBase64
|
||||
? Buffer.from(data.logoBase64, "base64")
|
||||
: undefined;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const PRIMARY = data.colorPrimario || "#2563eb";
|
||||
const DARK = data.colorSecundario || "#1e293b";
|
||||
const MUTED = "#64748b";
|
||||
const BORDER = "#cbd5e1";
|
||||
const LIGHT_BG = "#f1f5f9";
|
||||
const WHITE = "#ffffff";
|
||||
|
||||
const doc = new PDFDocument({
|
||||
size: "LETTER",
|
||||
margins: { top: 45, bottom: 55, left: 50, right: 50 },
|
||||
bufferPages: true,
|
||||
});
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
doc.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
doc.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
doc.on("error", reject);
|
||||
|
||||
const pw = doc.page.width;
|
||||
const ph = doc.page.height;
|
||||
const m = doc.page.margins;
|
||||
const W = pw - m.left - m.right;
|
||||
const L = m.left;
|
||||
const maxY = ph - m.bottom - 5;
|
||||
|
||||
function need(h: number, y: number): number {
|
||||
if (y + h > maxY) {
|
||||
doc.addPage();
|
||||
return m.top;
|
||||
}
|
||||
return y;
|
||||
}
|
||||
|
||||
function rowBg(y: number, h: number, bg: string) {
|
||||
doc.save();
|
||||
doc.rect(L, y, W, h).fill(bg);
|
||||
doc.moveTo(L, y + h).lineTo(L + W, y + h).strokeColor(BORDER).lineWidth(0.3).stroke();
|
||||
doc.restore();
|
||||
}
|
||||
|
||||
function txtHeight(str: string, width: number, size: number): number {
|
||||
return doc.font("Helvetica").fontSize(size).heightOfString(str, { width });
|
||||
}
|
||||
|
||||
// ── PAGE 1: COVER ──────────────────────────────
|
||||
doc.rect(0, 0, pw, ph).fill(WHITE);
|
||||
|
||||
if (logoBuffer) {
|
||||
try { doc.image(logoBuffer, L, 55, { height: 65 }); } catch {}
|
||||
} else {
|
||||
doc.font("Helvetica-Bold").fontSize(28).fillColor(PRIMARY).text("UJ", L, 55);
|
||||
doc.font("Helvetica").fontSize(9).fillColor(MUTED).text("Uriel Jareth Consulting", L + 48, 70);
|
||||
}
|
||||
|
||||
const barY = logoBuffer ? 145 : 130;
|
||||
doc.rect(L, barY, W, 4).fill(PRIMARY);
|
||||
|
||||
doc.font("Helvetica-Bold").fontSize(36).fillColor(DARK).text("Cotizacion", L, barY + 24);
|
||||
doc.font("Helvetica").fontSize(18).fillColor(PRIMARY).text(data.numero, L, barY + 68);
|
||||
|
||||
let iy = barY + 110;
|
||||
const cL = L;
|
||||
const cR = L + W * 0.52;
|
||||
|
||||
const infoL: [string, string][] = [
|
||||
["Cliente", data.clienteNombre],
|
||||
...(data.clienteEmpresa ? [["Empresa", data.clienteEmpresa]] as [string, string][] : []),
|
||||
["Proyecto", data.proyecto],
|
||||
["Asesor", data.asesorNombre],
|
||||
];
|
||||
const infoR: [string, string][] = [
|
||||
["Fecha", fmtDate(data.fecha)],
|
||||
["Vigencia", fmtDate(data.vigencia)],
|
||||
["Moneda", data.moneda],
|
||||
["Esquema", data.esquemaPago],
|
||||
];
|
||||
|
||||
for (let i = 0; i < Math.max(infoL.length, infoR.length); i++) {
|
||||
if (i < infoL.length) {
|
||||
doc.font("Helvetica").fontSize(9).fillColor(MUTED).text(infoL[i][0], cL, iy);
|
||||
doc.font("Helvetica").fontSize(11).fillColor(DARK).text(infoL[i][1], cL, iy + 12);
|
||||
}
|
||||
if (i < infoR.length) {
|
||||
doc.font("Helvetica").fontSize(9).fillColor(MUTED).text(infoR[i][0], cR, iy);
|
||||
doc.font("Helvetica").fontSize(11).fillColor(DARK).text(infoR[i][1], cR, iy + 12);
|
||||
}
|
||||
iy += 32;
|
||||
}
|
||||
|
||||
// ── PAGE 2+: RESUMEN ──────────────────────────
|
||||
doc.addPage();
|
||||
let y = m.top;
|
||||
|
||||
if (logoBuffer) {
|
||||
try { doc.image(logoBuffer, L + W - 70, m.top - 5, { height: 22 }); } catch {}
|
||||
}
|
||||
|
||||
doc.rect(L, y, 4, 16).fill(PRIMARY);
|
||||
doc.font("Helvetica-Bold").fontSize(15).fillColor(DARK).text("Hoja Resumen", L + 12, y + 1);
|
||||
y += 26;
|
||||
|
||||
doc.font("Helvetica").fontSize(8).fillColor(MUTED);
|
||||
doc.text(`En atencion a: ${data.clienteEmpresa || data.clienteNombre}`, L, y);
|
||||
doc.text(`No. Cotizacion: ${data.numero}`, L + W * 0.45, y);
|
||||
y += 11;
|
||||
doc.text(`Asesor: ${data.asesorNombre}`, L, y);
|
||||
doc.text(`Fecha: ${fmtDate(data.fecha)} | Moneda: ${data.moneda}`, L + W * 0.45, y);
|
||||
y += 16;
|
||||
|
||||
const colNombre = L;
|
||||
const colTipo = L + W - 200;
|
||||
const colTiempo = L + W - 120;
|
||||
const colPrecio = L + W - 60;
|
||||
|
||||
rowBg(y, 16, LIGHT_BG);
|
||||
doc.font("Helvetica-Bold").fontSize(7).fillColor(DARK);
|
||||
doc.text("Servicio", colNombre + 6, y + 4);
|
||||
doc.text("Tipo", colTipo + 4, y + 4);
|
||||
doc.text("Entrega", colTiempo + 4, y + 4);
|
||||
doc.text("Precio", colPrecio, y + 4, { width: 60, align: "right" });
|
||||
y += 18;
|
||||
|
||||
const unicos = data.servicios.filter((s) => s.tipoPago === "unico");
|
||||
const mensuales = data.servicios.filter((s) => s.tipoPago === "mensual");
|
||||
|
||||
function drawSection(servicios: ServicioPDF[], tipoLabel: string, tituloTotal: string) {
|
||||
if (servicios.length === 0) return y;
|
||||
let currentFase = -1;
|
||||
|
||||
for (const serv of servicios) {
|
||||
if (serv.fase !== currentFase) {
|
||||
currentFase = serv.fase;
|
||||
y = need(20, y);
|
||||
doc.rect(L, y, W, 14).fill(LIGHT_BG);
|
||||
doc.font("Helvetica-Bold").fontSize(7).fillColor(PRIMARY);
|
||||
doc.text(FASES[serv.fase] || `FASE ${serv.fase}`, L + 6, y + 3);
|
||||
y += 16;
|
||||
}
|
||||
|
||||
const servH = 13 + (serv.entregables ? Math.ceil(serv.entregables.length / 2) * 8 : 0) + 5;
|
||||
y = need(servH, y);
|
||||
|
||||
doc.font("Helvetica").fontSize(8).fillColor(DARK);
|
||||
doc.text(serv.nombre, colNombre + 6, y, { width: colTipo - colNombre - 16 });
|
||||
doc.font("Helvetica").fontSize(7).fillColor(MUTED);
|
||||
doc.text(tipoLabel, colTipo + 4, y);
|
||||
doc.text(serv.tiempoEntrega, colTiempo + 4, y, { width: 56 });
|
||||
doc.font("Helvetica-Bold").fontSize(8).fillColor(DARK);
|
||||
doc.text(fmt(serv.precio), colPrecio, y, { width: 60, align: "right" });
|
||||
y += 13;
|
||||
|
||||
if (serv.entregables && serv.entregables.length > 0) {
|
||||
const col1X = colNombre + 10;
|
||||
const col2X = colNombre + W * 0.48;
|
||||
const colW = W * 0.44;
|
||||
const half = Math.ceil(serv.entregables.length / 2);
|
||||
for (let i = 0; i < half; i++) {
|
||||
const e1 = serv.entregables[i];
|
||||
const e2 = i + half < serv.entregables.length ? serv.entregables[i + half] : null;
|
||||
doc.font("Helvetica").fontSize(6).fillColor(MUTED);
|
||||
doc.text(`\u2022 ${e1}`, col1X, y, { width: colW });
|
||||
if (e2) doc.text(`\u2022 ${e2}`, col2X, y, { width: colW });
|
||||
y += 8;
|
||||
}
|
||||
}
|
||||
|
||||
doc.save();
|
||||
doc.moveTo(colNombre + 6, y).lineTo(L + W, y).strokeColor("#e5e7eb").lineWidth(0.2).stroke();
|
||||
doc.restore();
|
||||
y += 4;
|
||||
}
|
||||
|
||||
y += 3;
|
||||
const total = servicios.reduce((s, x) => s + x.precio, 0);
|
||||
rowBg(y, 18, "#f8fafc");
|
||||
doc.font("Helvetica-Bold").fontSize(8.5).fillColor(PRIMARY);
|
||||
doc.text(tituloTotal, colNombre + 6, y + 4);
|
||||
doc.text(fmt(total), colPrecio, y + 4, { width: 60, align: "right" });
|
||||
y += 22;
|
||||
doc.font("Helvetica").fontSize(6).fillColor(MUTED);
|
||||
doc.text("(Precios en Moneda Nacional, no incluyen IVA)", colNombre + 6, y);
|
||||
y += 12;
|
||||
return y;
|
||||
}
|
||||
|
||||
if (unicos.length > 0) y = drawSection(unicos, "Unico", "Total Pago Unico");
|
||||
if (mensuales.length > 0) y = drawSection(mensuales, "Mensual", "Total Pago Mensual");
|
||||
|
||||
if (data.planBucefaloNivel) {
|
||||
y = need(20, y);
|
||||
const label = data.planBucefaloNivel.charAt(0).toUpperCase() + data.planBucefaloNivel.slice(1);
|
||||
rowBg(y, 14, LIGHT_BG);
|
||||
doc.font("Helvetica-Bold").fontSize(7.5).fillColor(DARK).text(`Plan Bucefalo CRM - ${label}`, colNombre + 6, y + 3);
|
||||
doc.font("Helvetica-Bold").text(fmt(data.planBucefaloPrecio), colPrecio, y + 3, { width: 60, align: "right" });
|
||||
y += 18;
|
||||
}
|
||||
|
||||
if (data.incluirBonos) {
|
||||
y = need(90, y);
|
||||
y += 4;
|
||||
doc.rect(L, y, 3, 10).fill(PRIMARY);
|
||||
doc.font("Helvetica-Bold").fontSize(9).fillColor(DARK).text("Bonos (Pago en una exhibicion)", L + 10, y);
|
||||
y += 16;
|
||||
const bonos = [
|
||||
"Bono 1: 30 min mensuales en servicios Centinela (Sitio Web)",
|
||||
"Bono 2: Workshop Estrategico de Buyer Persona",
|
||||
"Bono 3: Workshop de Propuestas de Valor y Oferta Irresistible",
|
||||
"Bono 4: 1 ano de Membresia Premium",
|
||||
"Bono 5: Un mes gratis de Bucefalo CRM",
|
||||
"Bono 6: Script de Ventas con mas de 100 complementos",
|
||||
];
|
||||
for (const b of bonos) {
|
||||
y = need(11, y);
|
||||
doc.font("Helvetica").fontSize(7).fillColor(DARK).text(`\u2713 ${b}`, L + 8, y, { width: W - 16 });
|
||||
y += 11;
|
||||
}
|
||||
}
|
||||
|
||||
// ── T&C PAGE ──────────────────────────────────
|
||||
doc.addPage();
|
||||
y = m.top;
|
||||
|
||||
if (logoBuffer) {
|
||||
try { doc.image(logoBuffer, L + W - 70, m.top - 5, { height: 22 }); } catch {}
|
||||
}
|
||||
|
||||
doc.rect(L, y, 4, 16).fill(PRIMARY);
|
||||
doc.font("Helvetica-Bold").fontSize(15).fillColor(DARK).text("Terminos y Condiciones", L + 12, y + 1);
|
||||
y += 28;
|
||||
|
||||
function sectionTitle(title: string, yy: number): number {
|
||||
yy = need(20, yy);
|
||||
doc.rect(L, yy, 3, 9).fill(PRIMARY);
|
||||
doc.font("Helvetica-Bold").fontSize(9).fillColor(DARK).text(title, L + 10, yy);
|
||||
return yy + 15;
|
||||
}
|
||||
|
||||
function drawBullets(title: string, items: string[], yStart: number): number {
|
||||
let yy = sectionTitle(title, yStart);
|
||||
for (const t of items) {
|
||||
const h = txtHeight(`\u2022 ${t}`, W - 4, 7.5);
|
||||
yy = need(h + 4, yy);
|
||||
doc.font("Helvetica").fontSize(7.5).fillColor(DARK).text(`\u2022 ${t}`, L + 2, yy, { width: W - 4 });
|
||||
yy += h + 4;
|
||||
}
|
||||
return yy + 6;
|
||||
}
|
||||
|
||||
y = drawBullets("Condiciones", [
|
||||
"Esta cotizacion tiene una vigencia de 15 dias habiles.",
|
||||
"Cualquier ajuste al proyecto despues de la aprobacion del contenido afectara la fecha de entrega y por consiguiente el costo.",
|
||||
"El cliente debera proporcionar la informacion solicitada por Uriel Jareth Consulting en tiempo y forma.",
|
||||
"Si la falta de informacion provoca un excedente en los plazos de entrega del proyecto, las horas adicionales de servicio se cotizaran por separado.",
|
||||
"Los pagos correspondientes a los servicios mensuales deberan realizarse en los primeros 5 dias del mes.",
|
||||
"Todo el material e informacion necesarios para la realizacion del sitio web deberan ser entregados en un plazo maximo de 40 dias naturales a partir del arranque del proyecto.",
|
||||
], y);
|
||||
|
||||
y = drawBullets("Que no incluye el proyecto?", [
|
||||
"Generacion de disenos, videos, traducciones, cambios de divisas y unidades, o cualquier servicio externo a lo cotizado.",
|
||||
"Redaccion de entradas de Blog.",
|
||||
"Integracion de Servicios de terceros ajenos a los cotizados.",
|
||||
"Servicio de Recuperacion de Accesos de: Google Analytics, Google Tag Manager, Google Search Console, Google Ads, y Meta Ads.",
|
||||
"Creacion de Redes Sociales (En caso de requerir el servicio incluira un costo adicional).",
|
||||
], y);
|
||||
|
||||
y = drawBullets("Notas", [
|
||||
"El presente proyecto debera tener un responsable oficial.",
|
||||
"La Hora Centinela tiene un precio de $700.00 MXN.",
|
||||
"Los archivos editables/fuente (AI, PSD) son propiedad intelectual de la agencia. Si requiere los archivos editables, estos pueden ser adquiridos abonando una tarifa de liberacion (buy-out fee).",
|
||||
"Si el proyecto se pausa por razones ajenas a Uriel Jareth Consulting, esto generara costo extra del 15% al 30% para retomar el proyecto.",
|
||||
], y);
|
||||
|
||||
y += 6;
|
||||
y = need(110, y);
|
||||
doc.rect(L, y, 3, 9).fill(PRIMARY);
|
||||
doc.font("Helvetica-Bold").fontSize(9).fillColor(DARK).text("Datos Bancarios", L + 10, y);
|
||||
y += 16;
|
||||
|
||||
const cfg = data.configBancaria || {};
|
||||
const razonSocial = cfg.razon_social || "URIEL JARETH ALVARADO ORTIZ";
|
||||
const rfc = cfg.rfc || "AAOU970201SU7";
|
||||
const clabeNac = cfg.clabe_interbancaria || cfg.cuenta_nacional || "";
|
||||
const cuentaNac = cfg.cuenta_nacional || "";
|
||||
const bancoNac = cfg.cuenta_nacional ? "BBVA" : "";
|
||||
const cuentaInt = (cfg.cuenta_internacional_swift || cfg.cuenta_internacional || "").split("\n").filter(Boolean);
|
||||
const swiftMatch = cfg.cuenta_internacional_swift?.match(/SWIFT[^:]*:\s*(\S+)/i);
|
||||
const clabeIntMatch = cfg.cuenta_internacional_swift?.match(/CLABE[^:]*:\s*(\S+)/i);
|
||||
const swift = swiftMatch?.[1] || "BCMRMXMMPYM";
|
||||
const clabeInt = clabeIntMatch?.[1] || "";
|
||||
|
||||
const boxH = 48;
|
||||
doc.save();
|
||||
doc.rect(L, y, W, boxH).fill(LIGHT_BG).stroke(BORDER);
|
||||
doc.font("Helvetica-Bold").fontSize(7).fillColor(DARK).text("Transferencia Nacional", L + 8, y + 4);
|
||||
doc.font("Helvetica").fontSize(6.5).fillColor(DARK);
|
||||
if (cuentaNac) doc.text(`Cuenta: ${cuentaNac}`, L + 8, y + 15);
|
||||
if (clabeNac) doc.text(`CLABE: ${clabeNac}`, L + W * 0.45, y + 15);
|
||||
doc.text(`Razon Social: ${razonSocial}`, L + 8, y + 26);
|
||||
doc.text(`RFC: ${rfc}`, L + W * 0.45, y + 26);
|
||||
if (bancoNac) doc.text(`Banco: ${bancoNac}`, L + 8, y + 37);
|
||||
doc.restore();
|
||||
y += boxH + 6;
|
||||
|
||||
y = need(boxH + 6, y);
|
||||
doc.save();
|
||||
doc.rect(L, y, W, boxH).fill(LIGHT_BG).stroke(BORDER);
|
||||
doc.font("Helvetica-Bold").fontSize(7).fillColor(DARK).text("Transferencia Internacional", L + 8, y + 4);
|
||||
doc.font("Helvetica").fontSize(6.5).fillColor(DARK);
|
||||
doc.text(`Beneficiario: ${razonSocial}`, L + 8, y + 15);
|
||||
if (clabeInt) doc.text(`CLABE: ${clabeInt}`, L + W * 0.45, y + 15);
|
||||
doc.text(`Banco: BBVA Mexico`, L + 8, y + 26);
|
||||
doc.text(`SWIFT: ${swift}`, L + W * 0.45, y + 26);
|
||||
doc.restore();
|
||||
|
||||
// ── ADD FOOTERS TO ALL PAGES ──────────────────
|
||||
const savedBottom = doc.page.margins.bottom;
|
||||
const range = doc.bufferedPageRange();
|
||||
for (let i = range.start; i < range.start + range.count; i++) {
|
||||
doc.switchToPage(i);
|
||||
doc.page.margins.bottom = 0;
|
||||
doc.save();
|
||||
doc.moveTo(L, ph - 42).lineTo(L + W, ph - 42).strokeColor(BORDER).lineWidth(0.5).stroke();
|
||||
doc.font("Helvetica").fontSize(6).fillColor(MUTED);
|
||||
doc.text(
|
||||
"Uriel Jareth Consulting",
|
||||
L, ph - 35, { width: W, align: "center", lineBreak: false }
|
||||
);
|
||||
doc.text(
|
||||
"urieljareth.com | [email protected] | (445) 182 9943",
|
||||
L, ph - 26, { width: W, align: "center", lineBreak: false }
|
||||
);
|
||||
doc.restore();
|
||||
doc.page.margins.bottom = savedBottom;
|
||||
}
|
||||
|
||||
doc.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const servicioSchema = z.object({
|
||||
catalogoId: z.string().min(1),
|
||||
nombre: z.string().min(1),
|
||||
fase: z.number().int().min(0).max(3),
|
||||
tipoPago: z.enum(["unico", "mensual"]),
|
||||
precio: z.number().min(0),
|
||||
tiempoEntrega: z.string().min(1),
|
||||
entregables: z.array(z.string()),
|
||||
});
|
||||
|
||||
export const cotizacionPostSchema = z.object({
|
||||
numero: z.string().min(1),
|
||||
fecha: z.coerce.date(),
|
||||
vigencia: z.coerce.date(),
|
||||
moneda: z.enum(["MXN", "USD"]),
|
||||
tipoCambio: z.string(),
|
||||
proyecto: z.string(),
|
||||
esquemaPago: z.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual"]),
|
||||
incluirBonos: z.boolean(),
|
||||
incluirFinanciamiento: z.boolean(),
|
||||
observaciones: z.string(),
|
||||
asesorId: z.string().min(1),
|
||||
cliente: z.object({
|
||||
nombre: z.string().min(1, "Cliente nombre es requerido"),
|
||||
empresa: z.string(),
|
||||
email: z.string().email().or(z.literal("")),
|
||||
telefono: z.string(),
|
||||
}),
|
||||
servicios: z.array(servicioSchema),
|
||||
planBucefalo: z
|
||||
.object({
|
||||
nivel: z.string(),
|
||||
precio: z.number().min(0),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
export const cotizacionPutSchema = z.object({
|
||||
fecha: z.coerce.date(),
|
||||
vigencia: z.coerce.date(),
|
||||
moneda: z.enum(["MXN", "USD"]),
|
||||
tipoCambio: z.string(),
|
||||
proyecto: z.string(),
|
||||
esquemaPago: z.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual"]),
|
||||
incluirBonos: z.boolean(),
|
||||
incluirFinanciamiento: z.boolean(),
|
||||
observaciones: z.string(),
|
||||
cliente: z.object({
|
||||
nombre: z.string().min(1, "Cliente nombre es requerido"),
|
||||
empresa: z.string(),
|
||||
email: z.string().email().or(z.literal("")),
|
||||
telefono: z.string(),
|
||||
}),
|
||||
servicios: z.array(servicioSchema),
|
||||
planBucefalo: z
|
||||
.object({
|
||||
nivel: z.string(),
|
||||
precio: z.number().min(0),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
export const loginSchema = z.object({
|
||||
email: z.string().email("Email invalido"),
|
||||
password: z.string().min(1, "Password es requerido"),
|
||||
});
|
||||
|
||||
export const servicioCatalogoSchema = z.object({
|
||||
nombre: z.string().min(1, "Nombre es requerido"),
|
||||
descripcion: z.string().nullable(),
|
||||
fase: z.number().int().min(0).max(3),
|
||||
tipoPago: z.enum(["unico", "mensual"]),
|
||||
precioBase: z.number().min(0, "Precio debe ser positivo"),
|
||||
tiempoEntrega: z.string().min(1),
|
||||
entregablesDefault: z.array(z.string()),
|
||||
categoriaId: z.string().min(1, "Categoria es requerida"),
|
||||
variante: z.string().nullable(),
|
||||
orden: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export function validateOrError<T>(
|
||||
schema: z.ZodType<T>,
|
||||
data: unknown
|
||||
): T | { error: string } {
|
||||
const result = schema.safeParse(data);
|
||||
if (result.success) return result.data;
|
||||
return { error: result.error.issues.map((i) => i.message).join(", ") };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { create } from "zustand";
|
||||
|
||||
export interface ServicioSeleccionado {
|
||||
catalogoId: string;
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
notas?: string;
|
||||
}
|
||||
|
||||
export interface CotizacionDraft {
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string;
|
||||
clienteEmail: string;
|
||||
clienteTelefono: string;
|
||||
asesorId: string;
|
||||
asesorNombre: string;
|
||||
fecha: Date;
|
||||
vigencia: Date | null;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
incluirBonos: boolean;
|
||||
incluirFinanciamiento: boolean;
|
||||
planBucefaloNivel: string | null;
|
||||
servicios: ServicioSeleccionado[];
|
||||
observaciones: string;
|
||||
}
|
||||
|
||||
interface CotizacionStore {
|
||||
draft: CotizacionDraft;
|
||||
setField: <K extends keyof CotizacionDraft>(
|
||||
field: K,
|
||||
value: CotizacionDraft[K]
|
||||
) => void;
|
||||
toggleServicio: (servicio: ServicioSeleccionado) => void;
|
||||
updateServicio: (catalogoId: string, updates: Partial<ServicioSeleccionado>) => void;
|
||||
removeServicio: (catalogoId: string) => void;
|
||||
setServicios: (servicios: ServicioSeleccionado[]) => void;
|
||||
resetDraft: () => void;
|
||||
}
|
||||
|
||||
const initialDraft: CotizacionDraft = {
|
||||
clienteNombre: "",
|
||||
clienteEmpresa: "",
|
||||
clienteEmail: "",
|
||||
clienteTelefono: "",
|
||||
asesorId: "",
|
||||
asesorNombre: "",
|
||||
fecha: new Date(),
|
||||
vigencia: null,
|
||||
moneda: "MXN",
|
||||
tipoCambio: "NA",
|
||||
proyecto: "MKT Digital",
|
||||
esquemaPago: "Pago Unico/Mensual",
|
||||
incluirBonos: false,
|
||||
incluirFinanciamiento: false,
|
||||
planBucefaloNivel: null,
|
||||
servicios: [],
|
||||
observaciones: "",
|
||||
};
|
||||
|
||||
export const useCotizacionStore = create<CotizacionStore>((set) => ({
|
||||
draft: { ...initialDraft },
|
||||
|
||||
setField: (field, value) =>
|
||||
set((state) => ({ draft: { ...state.draft, [field]: value } })),
|
||||
|
||||
toggleServicio: (servicio) =>
|
||||
set((state) => {
|
||||
const exists = state.draft.servicios.find(
|
||||
(s) => s.catalogoId === servicio.catalogoId
|
||||
);
|
||||
if (exists) {
|
||||
return {
|
||||
draft: {
|
||||
...state.draft,
|
||||
servicios: state.draft.servicios.filter(
|
||||
(s) => s.catalogoId !== servicio.catalogoId
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
draft: {
|
||||
...state.draft,
|
||||
servicios: [...state.draft.servicios, servicio],
|
||||
},
|
||||
};
|
||||
}),
|
||||
|
||||
updateServicio: (catalogoId, updates) =>
|
||||
set((state) => ({
|
||||
draft: {
|
||||
...state.draft,
|
||||
servicios: state.draft.servicios.map((s) =>
|
||||
s.catalogoId === catalogoId ? { ...s, ...updates } : s
|
||||
),
|
||||
},
|
||||
})),
|
||||
|
||||
removeServicio: (catalogoId) =>
|
||||
set((state) => ({
|
||||
draft: {
|
||||
...state.draft,
|
||||
servicios: state.draft.servicios.filter(
|
||||
(s) => s.catalogoId !== catalogoId
|
||||
),
|
||||
},
|
||||
})),
|
||||
|
||||
setServicios: (servicios) =>
|
||||
set((state) => ({ draft: { ...state.draft, servicios } })),
|
||||
|
||||
resetDraft: () => set({ draft: { ...initialDraft } }),
|
||||
}));
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { verifySession } from "@/lib/auth";
|
||||
|
||||
const PUBLIC_PATHS = ["/login", "/api/auth/login", "/api/auth/logout"];
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
|
||||
const isPublic =
|
||||
PUBLIC_PATHS.some((p) => pathname.startsWith(p)) ||
|
||||
pathname.startsWith("/_next") ||
|
||||
pathname === "/favicon.ico";
|
||||
|
||||
if (isPublic) return NextResponse.next();
|
||||
|
||||
const token = request.cookies.get("cotizador-session")?.value;
|
||||
const isApi = pathname.startsWith("/api/");
|
||||
|
||||
if (!token) {
|
||||
if (isApi) {
|
||||
return NextResponse.json({ error: "No autenticado" }, { status: 401 });
|
||||
}
|
||||
return NextResponse.redirect(new URL("/login", request.url));
|
||||
}
|
||||
|
||||
const session = await verifySession(token);
|
||||
if (!session) {
|
||||
if (isApi) {
|
||||
const res = NextResponse.json({ error: "Sesion expirada" }, { status: 401 });
|
||||
res.cookies.set("cotizador-session", "", { maxAge: 0, path: "/" });
|
||||
return res;
|
||||
}
|
||||
const response = NextResponse.redirect(new URL("/login", request.url));
|
||||
response.cookies.set("cotizador-session", "", { maxAge: 0, path: "/" });
|
||||
return response;
|
||||
}
|
||||
|
||||
const requestHeaders = new Headers(request.headers);
|
||||
requestHeaders.set("x-user-id", session.userId);
|
||||
requestHeaders.set("x-user-role", session.role || "asesor");
|
||||
|
||||
return NextResponse.next({
|
||||
request: { headers: requestHeaders },
|
||||
});
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
Reference in New Issue
Block a user