Restaurar funcionalidades desde stash + setup de despliegue Coolify

- Recupera el trabajo revertido (doble propuesta, retainer, niveles, API Python) desde el stash de GitHub Desktop
- Dockerfile multi-stage para Next.js (migraciones automáticas al arrancar, seed opcional via RUN_SEED)
- docker-compose.coolify.yml: postgres + web + api con healthchecks y SERVICE_FQDN_*
- Endpoint público /api/health (verifica BD) para healthchecks
- seed.ts parametrizado: conexión DB_* y credenciales SEED_* por entorno (sin passwords hardcodeadas)
- .env.example, .dockerignore, uvicorn con --proxy-headers
- Limpieza: .xlsx y __pycache__ fuera del repo

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
2026-06-10 02:21:18 -06:00
co-authored by Claude Fable 5
parent c3f4449296
commit 69c74faabb
43 changed files with 3536 additions and 1139 deletions
+41 -25
View File
@@ -6,14 +6,12 @@ import {
Pencil,
Trash2,
X,
Check,
ChevronDown,
ChevronRight,
Loader2,
Package,
LayoutGrid,
Settings,
GripVertical,
Save,
FileDown,
Upload,
@@ -34,6 +32,7 @@ interface Servicio {
categoriaNombre: string;
categoriaColor: string;
variante: string | null;
nivel: string | null;
activo: boolean;
orden: number;
}
@@ -51,7 +50,7 @@ interface FasePaqueteUI {
id: string;
nombre: string;
orden: number;
servicios: { id: string; nombre: string; precioBase: number; tipoPago: string }[];
servicios: { id: string; nombre: string; precioBase: number; tipoPago: string; nivel: string | null }[];
}
interface PaqueteUI {
@@ -309,33 +308,36 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
<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">
<table className="w-full text-sm table-fixed">
<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-left px-4 py-3 font-medium text-muted w-28">Tipo</th>
<th className="text-left px-4 py-3 font-medium text-muted w-32">Tiempo</th>
<th className="text-right px-4 py-3 font-medium text-muted w-32">Precio</th>
<th className="text-center px-4 py-3 font-medium text-muted w-28">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 className="px-4 py-3 align-top">
<div className="font-medium flex flex-wrap items-center gap-2 min-w-0">
<span className="break-words">{s.nombre}</span>
{s.nivel && <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">{s.nivel}</span>}
</div>
{s.descripcion && <div className="text-xs text-muted mt-0.5 break-words">{s.descripcion}</div>}
</td>
<td className="px-4 py-3">
<td className="px-4 py-3 align-top">
<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">
<td className="px-4 py-3 text-muted text-xs align-top">{s.tiempoEntrega}</td>
<td className="px-4 py-3 text-right font-medium align-top">{formatCurrency(s.precioBase)}</td>
<td className="px-4 py-3 text-center text-muted align-top">{s.entregablesDefault.length}</td>
<td className="px-4 py-3 align-top">
<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" />
@@ -402,7 +404,7 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
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; })}
onClick={() => setExpandedPk((prev) => { const n = new Set(prev); if (n.has(pk.id)) n.delete(pk.id); else 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" />}
@@ -433,20 +435,23 @@ export function CatalogoClient({ initialServicios, initialCategorias, initialPaq
</div>
</div>
{fase.servicios.length > 0 ? (
<table className="w-full text-sm">
<table className="w-full text-sm table-fixed">
<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 className="px-4 py-2 align-top">
<div className="font-medium flex flex-wrap items-center gap-2 min-w-0">
<span className="break-words">{s.nombre}</span>
{s.nivel && <span className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-amber-100 text-amber-700">{s.nivel}</span>}
</div>
</td>
<td className="px-4 py-2">
<td className="px-4 py-2 align-top w-28">
<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">
<td className="px-4 py-2 text-right font-medium text-sm align-top w-32">{formatCurrency(s.precioBase)}</td>
<td className="px-4 py-2 w-10 align-top">
<button onClick={() => removeServFromFase(pk.id, fase.id, s.id)} className="text-muted hover:text-red-500">
<X className="w-4 h-4" />
</button>
@@ -633,6 +638,7 @@ function ServicioFormModal({
tiempoEntrega: servicio?.tiempoEntrega || "4 - 10 dias",
entregablesDefault: servicio?.entregablesDefault?.join("\n") || "",
variante: servicio?.variante || "",
nivel: servicio?.nivel || "",
fase: servicio?.fase ?? 1,
orden: servicio?.orden ?? 0,
activo: servicio?.activo ?? true,
@@ -647,7 +653,6 @@ function ServicioFormModal({
.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,
@@ -657,6 +662,7 @@ function ServicioFormModal({
tiempoEntrega: form.tiempoEntrega,
entregablesDefault: entregables,
variante: form.variante.trim() || null,
nivel: form.nivel.trim() || null,
fase: form.fase,
orden: form.orden,
activo: form.activo,
@@ -720,7 +726,17 @@ function ServicioFormModal({
<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&#10;Entregable 2&#10;..." 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 className="grid grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium mb-1">Nivel</label>
<select value={form.nivel} onChange={(e) => update("nivel", 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 nivel</option>
<option value="Emprendedor">Emprendedor</option>
<option value="PYME">PYME</option>
<option value="Empresario">Empresario</option>
<option value="Corporativo">Corporativo</option>
</select>
</div>
<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" />
+1
View File
@@ -39,6 +39,7 @@ export default async function CatalogoPage() {
categoriaNombre: s.categoriaRel?.nombre || "Sin categoria",
categoriaColor: s.categoriaRel?.color || "#6b7280",
variante: s.variante,
nivel: s.nivel,
activo: s.activo,
orden: s.orden,
}))}
+11 -10
View File
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useMemo, useState } from "react";
import { Search } from "lucide-react";
import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton";
@@ -10,21 +10,22 @@ interface Cliente {
empresa: string | null;
email: string | null;
telefono: string | null;
cotizaciones: { id: string }[];
_count: { cotizaciones: number };
}
export function ClientesList({ clientes }: { clientes: Cliente[] }) {
const [search, setSearch] = useState("");
const filtered = clientes.filter((c) => {
if (!search) return true;
const filtered = useMemo(() => {
if (!search) return clientes;
const q = search.toLowerCase();
return (
c.nombre.toLowerCase().includes(q) ||
(c.empresa || "").toLowerCase().includes(q) ||
(c.email || "").toLowerCase().includes(q)
return clientes.filter(
(c) =>
c.nombre.toLowerCase().includes(q) ||
(c.empresa || "").toLowerCase().includes(q) ||
(c.email || "").toLowerCase().includes(q)
);
});
}, [clientes, search]);
return (
<>
@@ -80,7 +81,7 @@ export function ClientesList({ clientes }: { clientes: Cliente[] }) {
<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}
{c._count.cotizaciones}
</span>
</td>
<td className="px-5 py-3 text-center">
+9 -2
View File
@@ -5,7 +5,14 @@ export const dynamic = "force-dynamic";
export default async function ClientesPage() {
const clientes = await prisma.cliente.findMany({
orderBy: { createdAt: "desc" },
include: { cotizaciones: { select: { id: true } } },
select: {
id: true,
nombre: true,
empresa: true,
email: true,
telefono: true,
_count: { select: { cotizaciones: true } },
},
});
return (
@@ -44,7 +51,7 @@ function ClientesListWrapper({
empresa: string | null;
email: string | null;
telefono: string | null;
cotizaciones: { id: string }[];
_count: { cotizaciones: number };
}[];
}) {
return <ClientesList clientes={clientes} />;
@@ -1,7 +1,7 @@
"use client";
import { useState, useRef } from "react";
import { Save, Upload, Trash2, Loader2, Image } from "lucide-react";
import { Save, Upload, Trash2, Loader2, Image as ImageIcon } from "lucide-react";
const SECTIONS = [
{
@@ -142,13 +142,14 @@ export function ConfiguracionClient({ initial }: { initial: Record<string, strin
<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 ? (
// eslint-disable-next-line @next/next/no-img-element -- logo es un data-URL base64, next/image no aplica
<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" />
<ImageIcon className="w-8 h-8 text-muted" />
)}
</div>
<div className="flex-1 space-y-2">
+11 -10
View File
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useMemo, useState } from "react";
import Link from "next/link";
import { Pencil, Search } from "lucide-react";
import { formatDate, formatCurrency } from "@/lib/calculators";
@@ -24,17 +24,18 @@ export function CotizacionesList({
}) {
const [search, setSearch] = useState("");
const filtered = cotizaciones.filter((cot) => {
if (!search) return true;
const filtered = useMemo(() => {
if (!search) return cotizaciones;
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 cotizaciones.filter(
(cot) =>
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)
);
});
}, [cotizaciones, search]);
return (
<>
@@ -46,14 +46,23 @@ export default async function EditarCotizacionPage({
incluirFinanciamiento: cot.incluirFinanciamiento,
observaciones: cot.observaciones || "",
planBucefaloNivel: cot.planBucefalo?.nivel || null,
esDoble: cot.esDoble,
opciones: (cot.opcionesMetadata as { "1"?: object; "2"?: object } | null) ?? {},
servicios: cot.servicios.map((s) => ({
catalogoId: s.servicioCatalogoId,
nombre: s.servicioCatalogo?.nombre || "Servicio",
catalogoId: s.servicioCatalogoId ?? `custom-${s.id}`,
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
fase: s.fase,
tipoPago: s.tipoPago,
precio: s.precio,
tiempoEntrega: s.tiempoEntrega,
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
esPersonalizado: s.esPersonalizado,
horas: s.horas ?? undefined,
tarifaHora: s.tarifaHora ?? undefined,
modeloCobro: s.modeloCobro ?? undefined,
montoMinimo: s.montoMinimo ?? undefined,
horasIncluidas: s.horasIncluidas ?? undefined,
opcion: s.opcion ?? undefined,
})),
estado: cot.estado,
};
+63 -4
View File
@@ -1,9 +1,9 @@
import { prisma } from "@/lib/db";
import { formatDate, formatCurrency, IVA_RATE } from "@/lib/calculators";
import { formatDate, formatCurrency, calcularTotalesOpcion, IVA_RATE, type MetaOpcion } 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 { ExportExcelButtonSaved, ExportPDFButtonSaved, PreviewPDFButtonSaved } from "@/components/ExportButtons";
import { DeleteCotizacionButton } from "./DeleteButton";
import { CambiarEstadoButtons } from "./CambiarEstadoButtons";
import { PreciosEditables } from "./PreciosEditables";
@@ -32,7 +32,7 @@ export default async function CotizacionDetailPage({
.filter((s) => s.tipoPago === "unico" && s.seleccionado)
.map((s) => ({
id: s.id,
nombre: s.servicioCatalogo?.nombre || "Servicio",
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
precio: s.precio,
}));
@@ -40,10 +40,18 @@ export default async function CotizacionDetailPage({
.filter((s) => s.tipoPago === "mensual" && s.seleccionado)
.map((s) => ({
id: s.id,
nombre: s.servicioCatalogo?.nombre || "Servicio",
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
precio: s.precio,
}));
const opcionesMeta = (cot.opcionesMetadata as { "1"?: MetaOpcion; "2"?: MetaOpcion } | null) ?? {};
const totalesOpcion = cot.esDoble
? {
"1": calcularTotalesOpcion(cot.servicios, "1"),
"2": calcularTotalesOpcion(cot.servicios, "2"),
}
: null;
return (
<div>
<div className="flex items-center justify-between mb-6">
@@ -62,6 +70,7 @@ export default async function CotizacionDetailPage({
</div>
</div>
<div className="flex items-center gap-2">
<PreviewPDFButtonSaved cotizacionId={cot.id} />
<ExportPDFButtonSaved cotizacionId={cot.id} />
<ExportExcelButtonSaved cotizacionId={cot.id} />
<Link
@@ -115,6 +124,56 @@ export default async function CotizacionDetailPage({
</div>
</div>
{cot.esDoble && totalesOpcion && (
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
<h2 className="font-semibold text-lg mb-4">
Doble propuesta — comparativa
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{(["1", "2"] as const).map((op) => {
const t = totalesOpcion[op];
const meta = opcionesMeta[op];
return (
<div key={op} className="border border-primary/30 rounded-lg p-4 bg-primary-light/10">
<h3 className="font-semibold text-primary">
Opcion {op}
{meta?.titulo ? `: ${meta.titulo}` : ""}
</h3>
{meta?.descripcion && (
<p className="text-sm text-muted mt-1 whitespace-pre-wrap">{meta.descripcion}</p>
)}
{meta?.noIncluye && (
<p className="text-xs text-muted mt-2">
<span className="font-medium">No incluye:</span>{" "}
<span className="whitespace-pre-wrap">{meta.noIncluye}</span>
</p>
)}
<div className="mt-3 pt-3 border-t border-border space-y-1 text-sm">
<div className="flex justify-between">
<span>Total unico (c/IVA)</span>
<span className="font-medium">{formatCurrency(t.totalUnico * (1 + IVA_RATE))}</span>
</div>
<div className="flex justify-between">
<span>Total mensual (c/IVA)</span>
<span className="font-medium">{formatCurrency(t.totalMensual * (1 + IVA_RATE))}</span>
</div>
{t.horas > 0 && (
<div className="flex justify-between text-muted text-xs">
<span>Horas estimadas</span>
<span>{t.horas} h</span>
</div>
)}
</div>
</div>
);
})}
</div>
<p className="text-xs text-muted mt-3">
Las partidas marcadas <b>Ambas</b> suman en las dos opciones. Edita la asignacion de cada partida desde <b>Editar</b>.
</p>
</div>
)}
<PreciosEditables
cotizacionId={cot.id}
serviciosUnicos={serviciosUnicos}
+1 -2
View File
@@ -4,14 +4,13 @@ import { prisma } from "@/lib/db";
export const dynamic = "force-dynamic";
export default async function NuevaCotizacionPage() {
const [servicios, asesores, clientes, paquetes] = await Promise.all([
const [servicios, asesores, 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: {
+11 -1
View File
@@ -8,7 +8,17 @@ 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 },
select: {
id: true,
numero: true,
estado: true,
fecha: true,
cliente: { select: { nombre: true, empresa: true } },
asesor: { select: { name: true } },
servicios: {
select: { tipoPago: true, seleccionado: true, precio: true },
},
},
});
return (
+10 -1
View File
@@ -17,7 +17,16 @@ export default async function DashboardPage() {
prisma.cotizacion.findMany({
take: 10,
orderBy: { createdAt: "desc" },
include: { cliente: true, asesor: true, servicios: true },
select: {
id: true,
numero: true,
fecha: true,
estado: true,
cliente: { select: { nombre: true, empresa: true } },
servicios: {
select: { tipoPago: true, seleccionado: true, precio: true },
},
},
}),
prisma.cliente.count(),
prisma.servicioCatalogo.count({ where: { activo: true } }),
+1
View File
@@ -19,6 +19,7 @@ export async function PUT(
tiempoEntrega: body.tiempoEntrega,
entregablesDefault: body.entregablesDefault || [],
variante: body.variante || null,
nivel: body.nivel || null,
activo: body.activo !== false,
orden: body.orden,
categoriaId: body.categoriaId || null,
+1
View File
@@ -35,6 +35,7 @@ export async function POST(request: NextRequest) {
entregablesDefault: parsed.data.entregablesDefault,
categoriaId: parsed.data.categoriaId,
variante: parsed.data.variante,
nivel: parsed.data.nivel ?? null,
activo: true,
orden: parsed.data.orden,
},
+44 -21
View File
@@ -74,6 +74,8 @@ export async function PUT(
esquemaPago,
incluirBonos,
incluirFinanciamiento,
esDoble,
opciones,
observaciones,
cliente,
servicios,
@@ -86,15 +88,15 @@ export async function PUT(
return NextResponse.json({ error: "No encontrada" }, { status: 404 });
}
let clienteIdFinal: string | undefined;
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;
clienteIdFinal = existingCliente.id;
await prisma.cliente.update({
where: { id: clienteId },
where: { id: clienteIdFinal },
data: {
email: cliente.email || existingCliente.email,
telefono: cliente.telefono || existingCliente.telefono,
@@ -109,18 +111,16 @@ export async function PUT(
telefono: cliente.telefono || null,
},
});
clienteId = newCliente.id;
clienteIdFinal = newCliente.id;
}
await prisma.cotizacion.update({
where: { id },
data: { clienteId },
});
}
const esDobleFinal = esDoble ?? existing.esDoble;
await prisma.cotizacion.update({
where: { id },
data: {
...(clienteIdFinal && { clienteId: clienteIdFinal }),
...(fecha && { fecha: new Date(fecha) }),
...(vigencia && { vigencia: new Date(vigencia) }),
...(moneda && { moneda }),
@@ -129,35 +129,58 @@ export async function PUT(
...(esquemaPago && { esquemaPago }),
...(incluirBonos !== undefined && { incluirBonos }),
...(incluirFinanciamiento !== undefined && { incluirFinanciamiento }),
...(esDoble !== undefined && { esDoble }),
...(esDoble !== undefined && { opcionesMetadata: esDoble ? opciones ?? {} : undefined }),
...(observaciones !== undefined && { observaciones }),
...(estado && ESTADOS_COTIZACION.includes(estado as typeof ESTADOS_COTIZACION[number]) && { estado }),
},
});
if (servicios && Array.isArray(servicios)) {
// El servicio Bucéfalo del catálogo se resuelve una sola vez, no por partida.
const necesitaBucefalo = servicios.some(
(s) => !s.esPersonalizado && s.catalogoId?.startsWith("bucefalo-")
);
const bucefaloCatalogoId = necesitaBucefalo
? (await prisma.servicioCatalogo.findFirst({
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
select: { id: true },
}))?.id ?? null
: null;
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: {
await tx.servicioCotizado.createMany({
data: servicios.map((serv) => {
let catalogoId: string | null;
if (serv.esPersonalizado) {
catalogoId = null;
} else if (serv.catalogoId?.startsWith("bucefalo-")) {
catalogoId = bucefaloCatalogoId;
} else {
catalogoId = serv.catalogoId;
}
return {
cotizacionId: id,
servicioCatalogoId: catalogoId,
nombre: serv.esPersonalizado ? serv.nombre : null,
esPersonalizado: serv.esPersonalizado ?? false,
horas: serv.esPersonalizado ? serv.horas ?? null : null,
tarifaHora: serv.esPersonalizado ? serv.tarifaHora ?? null : null,
modeloCobro: serv.modeloCobro ?? (serv.esPersonalizado ? "horas" : "fijo"),
montoMinimo: serv.esPersonalizado ? serv.montoMinimo ?? null : null,
horasIncluidas: serv.esPersonalizado ? serv.horasIncluidas ?? null : null,
opcion: esDobleFinal ? serv.opcion ?? "ambas" : null,
fase: serv.fase,
tipoPago: serv.tipoPago,
precio: serv.precio,
tiempoEntrega: serv.tiempoEntrega,
entregables: serv.entregables,
seleccionado: true,
},
});
}
};
}),
});
});
}
+38 -11
View File
@@ -22,6 +22,8 @@ export async function POST(request: NextRequest) {
esquemaPago,
incluirBonos,
incluirFinanciamiento,
esDoble,
opciones,
observaciones,
cliente,
asesorId,
@@ -49,6 +51,18 @@ export async function POST(request: NextRequest) {
const clienteIdFinal = clienteRecord.id;
// El servicio Bucéfalo del catálogo es el mismo para todas las partidas:
// se resuelve una sola vez fuera del loop de inserción.
const necesitaBucefalo = servicios.some(
(s) => !s.esPersonalizado && s.catalogoId.startsWith("bucefalo-")
);
const bucefaloCatalogoId = necesitaBucefalo
? (await prisma.servicioCatalogo.findFirst({
where: { categoriaRel: { nombre: "CRM" }, tipoPago: "mensual" },
select: { id: true },
}))?.id ?? null
: null;
const cotizacion = await prisma.$transaction(async (tx) => {
const cot = await tx.cotizacion.create({
data: {
@@ -61,6 +75,8 @@ export async function POST(request: NextRequest) {
esquemaPago,
incluirBonos,
incluirFinanciamiento,
esDoble: esDoble ?? false,
opcionesMetadata: esDoble ? opciones ?? {} : undefined,
observaciones: observaciones || null,
clienteId: clienteIdFinal,
asesorId,
@@ -68,25 +84,36 @@ export async function POST(request: NextRequest) {
},
});
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: {
await tx.servicioCotizado.createMany({
data: servicios.map((servicio) => {
let catalogoId: string | null;
if (servicio.esPersonalizado) {
catalogoId = null;
} else if (servicio.catalogoId.startsWith("bucefalo-")) {
catalogoId = bucefaloCatalogoId;
} else {
catalogoId = servicio.catalogoId;
}
return {
cotizacionId: cot.id,
servicioCatalogoId: catalogoId,
nombre: servicio.esPersonalizado ? servicio.nombre : null,
esPersonalizado: servicio.esPersonalizado ?? false,
horas: servicio.esPersonalizado ? servicio.horas ?? null : null,
tarifaHora: servicio.esPersonalizado ? servicio.tarifaHora ?? null : null,
modeloCobro: servicio.modeloCobro ?? (servicio.esPersonalizado ? "horas" : "fijo"),
montoMinimo: servicio.esPersonalizado ? servicio.montoMinimo ?? null : null,
horasIncluidas: servicio.esPersonalizado ? servicio.horasIncluidas ?? null : null,
opcion: esDoble ? servicio.opcion ?? "ambas" : null,
fase: servicio.fase,
tipoPago: servicio.tipoPago,
precio: servicio.precio,
tiempoEntrega: servicio.tiempoEntrega,
entregables: servicio.entregables,
seleccionado: true,
},
});
}
};
}),
});
if (planBucefalo) {
await tx.planBucefaloCotizacion.create({
+53 -328
View File
@@ -1,24 +1,8 @@
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 } };
}
}
import { buildCotizacionExcel, type ExcelData } from "@/lib/excel-builder";
export async function GET(
request: NextRequest,
@@ -27,325 +11,66 @@ export async function GET(
try {
const { id } = await params;
const cot = await prisma.cotizacion.findUnique({
where: { id },
include: {
cliente: true,
asesor: true,
servicios: { include: { servicioCatalogo: true } },
planBucefalo: true,
},
});
const [cot, branding, bancaria] = await Promise.all([
prisma.cotizacion.findUnique({
where: { id },
include: {
cliente: true,
asesor: true,
servicios: { include: { servicioCatalogo: true } },
planBucefalo: true,
},
}),
getConfigBranding(),
getConfigBancaria(),
]);
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 data: ExcelData = {
razonSocial: bancaria.razon_social || "Cotizador E3",
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
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 || s.nombre || "Servicio",
fase: s.fase,
tipoPago: s.tipoPago,
precio: s.precio,
tiempoEntrega: s.tiempoEntrega,
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
modeloCobro: s.modeloCobro,
esPersonalizado: s.esPersonalizado,
horas: s.horas,
tarifaHora: s.tarifaHora,
montoMinimo: s.montoMinimo,
horasIncluidas: s.horasIncluidas,
opcion: s.opcion,
})),
esDoble: cot.esDoble,
opcionesMetadata: cot.opcionesMetadata as never,
planBucefaloNivel: cot.planBucefalo?.nivel ?? null,
planBucefaloPrecio: cot.planBucefalo?.precio ?? null,
colorPrimario: branding.colorPrimario || "#2563eb",
colorSecundario: branding.colorSecundario || "#1e293b",
};
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, {
const buffer = await buildCotizacionExcel(data);
return new NextResponse(new Uint8Array(buffer), {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="${sanitizeFilename(empresa)} - ${sanitizeFilename(cot.cliente.nombre)} - ${cot.numero}.xlsx"`,
+51 -304
View File
@@ -1,23 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import ExcelJS from "exceljs";
import { calcularVigencia, bucefaloPrecio, sanitizeFilename } from "@/lib/calculators";
import { calcularVigencia, 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 } };
}
}
import { buildCotizacionExcel, type ExcelData } from "@/lib/excel-builder";
export async function POST(request: NextRequest) {
try {
@@ -40,303 +24,66 @@ export async function POST(request: NextRequest) {
precio: number;
tiempoEntrega: string;
entregables: string[];
esPersonalizado?: boolean;
horas?: number;
tarifaHora?: number;
modeloCobro?: string;
montoMinimo?: number;
horasIncluidas?: number;
opcion?: string;
}[];
planBucefaloNivel: string | null;
observaciones: string;
esDoble?: boolean;
opciones?: { "1"?: { titulo?: string; descripcion?: string; noIncluye?: string }; "2"?: { titulo?: string; descripcion?: string; noIncluye?: 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 [branding, bancaria] = await Promise.all([
getConfigBranding(),
getConfigBancaria(),
]);
const workbook = new ExcelJS.Workbook();
workbook.creator = "Cotizador E3";
workbook.created = new Date();
const data: ExcelData = {
razonSocial: bancaria.razon_social || "Cotizador E3",
domicilioFiscal: bancaria.domicilio_fiscal || undefined,
numero: "BORRADOR",
clienteNombre: draft.clienteNombre,
clienteEmpresa: draft.clienteEmpresa,
asesorNombre: draft.asesorNombre,
fecha: fechaCot,
vigencia: calcularVigencia(fechaCot),
moneda: draft.moneda,
tipoCambio: draft.tipoCambio,
proyecto: draft.proyecto,
esquemaPago: draft.esquemaPago,
servicios: draft.servicios.map((s) => ({
nombre: s.nombre,
fase: s.fase,
tipoPago: s.tipoPago,
precio: s.precio,
tiempoEntrega: s.tiempoEntrega,
entregables: s.entregables ?? [],
modeloCobro: s.modeloCobro,
esPersonalizado: s.esPersonalizado,
horas: s.horas,
tarifaHora: s.tarifaHora,
montoMinimo: s.montoMinimo,
horasIncluidas: s.horasIncluidas,
opcion: s.opcion,
})),
esDoble: draft.esDoble,
opcionesMetadata: draft.esDoble ? draft.opciones ?? null : null,
planBucefaloNivel: draft.planBucefaloNivel,
colorPrimario: branding.colorPrimario || "#2563eb",
colorSecundario: branding.colorSecundario || "#1e293b",
};
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, {
const buffer = await buildCotizacionExcel(data);
return new NextResponse(new Uint8Array(buffer), {
headers: {
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="${sanitizeFilename(empresa)} - ${sanitizeFilename(draft.clienteNombre)} - BORRADOR.xlsx"`,
+23 -14
View File
@@ -10,23 +10,23 @@ export async function GET(
) {
try {
const { id } = await params;
const cot = await prisma.cotizacion.findUnique({
where: { id },
include: {
cliente: true,
asesor: true,
servicios: { include: { servicioCatalogo: true } },
planBucefalo: true,
},
});
const [cot, config, branding] = await Promise.all([
prisma.cotizacion.findUnique({
where: { id },
include: {
cliente: true,
asesor: true,
servicios: { include: { servicioCatalogo: true } },
planBucefalo: true,
},
}),
getConfigBancaria(),
getConfigBranding(),
]);
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}`;
@@ -42,13 +42,22 @@ export async function GET(
proyecto: cot.proyecto,
esquemaPago: cot.esquemaPago,
servicios: cot.servicios.filter((s) => s.seleccionado).map((s) => ({
nombre: s.servicioCatalogo?.nombre || "Servicio",
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
fase: s.fase,
tipoPago: s.tipoPago,
precio: s.precio,
tiempoEntrega: s.tiempoEntrega,
entregables: Array.isArray(s.entregables) ? (s.entregables as string[]) : [],
esPersonalizado: s.esPersonalizado,
horas: s.horas ?? undefined,
tarifaHora: s.tarifaHora ?? undefined,
modeloCobro: s.modeloCobro ?? undefined,
montoMinimo: s.montoMinimo ?? undefined,
horasIncluidas: s.horasIncluidas ?? undefined,
opcion: s.opcion ?? undefined,
})),
esDoble: cot.esDoble,
opcionesMetadata: cot.opcionesMetadata as never,
planBucefaloNivel: cot.planBucefalo?.nivel || null,
planBucefaloPrecio: cot.planBucefalo?.precio || 0,
incluirBonos: cot.incluirBonos,
+11
View File
@@ -24,9 +24,18 @@ export async function POST(request: NextRequest) {
precio: number;
tiempoEntrega: string;
entregables: string[];
esPersonalizado?: boolean;
horas?: number;
tarifaHora?: number;
modeloCobro?: string;
montoMinimo?: number;
horasIncluidas?: number;
opcion?: string;
}[];
planBucefaloNivel: string | null;
observaciones: string;
esDoble?: boolean;
opciones?: { "1"?: { titulo?: string; descripcion?: string; noIncluye?: string }; "2"?: { titulo?: string; descripcion?: string; noIncluye?: string } };
};
};
@@ -49,6 +58,8 @@ export async function POST(request: NextRequest) {
proyecto: draft.proyecto,
esquemaPago: draft.esquemaPago,
servicios: draft.servicios,
esDoble: draft.esDoble,
opcionesMetadata: draft.esDoble ? draft.opciones ?? null : null,
planBucefaloNivel: draft.planBucefaloNivel,
planBucefaloPrecio: draft.planBucefaloNivel ? bucefaloPrecio(draft.planBucefaloNivel) : 0,
incluirBonos: draft.incluirBonos,
+500 -8
View File
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
Save,
@@ -14,6 +14,9 @@ import {
Mail,
Phone,
Package,
Clock,
Plus,
Trash2,
} from "lucide-react";
import clsx from "clsx";
import {
@@ -24,7 +27,12 @@ import {
calcularVigencia,
generarNumeroCotizacion,
bucefaloPrecio,
calcularPrecioHoras,
describirRetainer,
calcularTotalesOpcion,
TARIFA_HORA_DEFAULT,
} from "@/lib/calculators";
import type { MetaOpcion } from "@/lib/calculators";
import {
useCotizacionStore,
ServicioSeleccionado,
@@ -32,6 +40,7 @@ import {
import {
ExportPDFButtonDraft,
ExportExcelButtonDraft,
PreviewPDFButtonDraft,
} from "@/components/ExportButtons";
export interface ServicioCatalogo {
@@ -75,6 +84,8 @@ export interface ExistingData {
planBucefaloNivel: string | null;
estado: string;
servicios: ServicioSeleccionado[];
esDoble?: boolean;
opciones?: { "1"?: MetaOpcion; "2"?: MetaOpcion };
}
export interface PaqueteServicio {
@@ -153,11 +164,18 @@ export function CotizacionForm({
store.setField("incluirFinanciamiento", existingData.incluirFinanciamiento);
store.setField("observaciones", existingData.observaciones);
store.setField("planBucefaloNivel", existingData.planBucefaloNivel);
store.setField("esDoble", existingData.esDoble ?? false);
store.setField("opciones", existingData.opciones ?? {});
store.setServicios(existingData.servicios);
}
}, [mode, existingData]);
const selectedIds = new Set(store.draft.servicios.map((s) => s.catalogoId));
const esDoble = store.draft.esDoble;
const selectedIds = useMemo(
() => new Set(store.draft.servicios.map((s) => s.catalogoId)),
[store.draft.servicios]
);
const toggleFase = (fase: number) => {
setExpandedFases((prev) => {
@@ -197,6 +215,99 @@ export function CotizacionForm({
store.updateServicio(catalogoId, { precio });
};
const handleAddCustom = () => {
const id = `custom-${crypto.randomUUID()}`;
store.toggleServicio({
catalogoId: id,
nombre: "",
fase: 1,
tipoPago: "unico",
precio: calcularPrecioHoras(1, TARIFA_HORA_DEFAULT),
tiempoEntrega: "A convenir",
entregables: [],
esPersonalizado: true,
horas: 1,
tarifaHora: TARIFA_HORA_DEFAULT,
});
};
const handleCustomHoras = (catalogoId: string, horas: number) => {
const s = store.draft.servicios.find((x) => x.catalogoId === catalogoId);
store.updateServicio(catalogoId, {
horas,
precio: calcularPrecioHoras(horas, s?.tarifaHora ?? TARIFA_HORA_DEFAULT),
});
};
const handleCustomTarifa = (catalogoId: string, tarifaHora: number) => {
const s = store.draft.servicios.find((x) => x.catalogoId === catalogoId);
store.updateServicio(catalogoId, {
tarifaHora,
precio: calcularPrecioHoras(s?.horas ?? 0, tarifaHora),
});
};
const handleAddRetainer = () => {
const id = `custom-${crypto.randomUUID()}`;
store.toggleServicio({
catalogoId: id,
nombre: "",
fase: 1,
tipoPago: "mensual",
precio: 0,
tiempoEntrega: "Mensual",
entregables: [],
esPersonalizado: true,
modeloCobro: "retainer",
montoMinimo: 0,
horasIncluidas: 40,
tarifaHora: TARIFA_HORA_DEFAULT,
});
};
// Cambia el modelo de cobro de una partida y recalcula su precio.
const handleModeloChange = (catalogoId: string, modelo: string) => {
const s = store.draft.servicios.find((x) => x.catalogoId === catalogoId);
if (!s) return;
if (modelo === "retainer") {
store.updateServicio(catalogoId, {
modeloCobro: "retainer",
tipoPago: "mensual",
montoMinimo: s.montoMinimo ?? 0,
horasIncluidas: s.horasIncluidas ?? 40,
tarifaHora: s.tarifaHora ?? TARIFA_HORA_DEFAULT,
precio: s.montoMinimo ?? 0,
});
} else {
store.updateServicio(catalogoId, {
modeloCobro: "horas",
precio: calcularPrecioHoras(s.horas ?? 1, s.tarifaHora ?? TARIFA_HORA_DEFAULT),
});
}
};
// Retainer: el precio cotizado es el monto minimo mensual. La tarifa/hora y las
// horas incluidas son informativas (las horas adicionales se facturan aparte).
const handleRetainerMonto = (catalogoId: string, montoMinimo: number) => {
store.updateServicio(catalogoId, { montoMinimo, precio: montoMinimo });
};
const customServicios = store.draft.servicios.filter((s) => s.esPersonalizado);
// Selector de opcion (1 / 2 / ambas) para una partida en modo doble propuesta.
const opcionSelect = (catalogoId: string, value?: string) => (
<select
value={value ?? "ambas"}
onChange={(e) => store.updateServicio(catalogoId, { opcion: e.target.value })}
className="px-2 py-1 border border-primary/40 rounded text-xs bg-white focus:outline-none focus:ring-1 focus:ring-primary"
title="Opcion a la que pertenece esta partida"
>
<option value="1">Opcion 1</option>
<option value="2">Opcion 2</option>
<option value="ambas">Ambas</option>
</select>
);
const buildRequestBody = () => ({
...(mode === "new" && {
numero: generarNumeroCotizacion(
@@ -217,6 +328,8 @@ export function CotizacionForm({
esquemaPago: store.draft.esquemaPago,
incluirBonos: store.draft.incluirBonos,
incluirFinanciamiento: store.draft.incluirFinanciamiento,
esDoble: store.draft.esDoble,
opciones: store.draft.esDoble ? store.draft.opciones : undefined,
observaciones: store.draft.observaciones,
cliente: {
nombre: store.draft.clienteNombre,
@@ -274,13 +387,26 @@ export function CotizacionForm({
const ivaUnico = totalUnico * IVA_RATE;
const ivaMensual = totalMensual * IVA_RATE;
// Totales por opcion (doble propuesta). "ambas" suma en las dos.
const totalesOpcion = useMemo(
() => ({
"1": calcularTotalesOpcion(store.draft.servicios, "1"),
"2": calcularTotalesOpcion(store.draft.servicios, "2"),
}),
[store.draft.servicios]
);
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 serviciosPorFase = useMemo(
() =>
[0, 1, 2, 3].reduce(
(acc, fase) => {
acc[fase] = servicios.filter((s) => s.fase === fase);
return acc;
},
{} as Record<number, ServicioCatalogo[]>
),
[servicios]
);
const title =
@@ -305,6 +431,7 @@ export function CotizacionForm({
)}
</div>
<div className="flex items-center gap-2">
<PreviewPDFButtonDraft draft={store.draft} />
<ExportPDFButtonDraft draft={store.draft} />
<ExportExcelButtonDraft draft={store.draft} />
<button
@@ -451,6 +578,72 @@ export function CotizacionForm({
</div>
</div>
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={esDoble}
onChange={(e) => store.setField("esDoble", e.target.checked)}
className="w-4 h-4 rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="font-semibold text-lg">Doble propuesta</span>
<span className="text-xs text-muted ml-2">
Presenta dos opciones comparables; el cliente elige una.
</span>
</label>
{esDoble && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
{(["1", "2"] as const).map((op) => (
<div
key={op}
className="border border-primary/30 rounded-lg p-4 bg-primary-light/10"
>
<h3 className="font-semibold text-sm mb-2 text-primary">
Opcion {op}
</h3>
<label className="block text-xs font-medium text-muted mb-1">
Titulo
</label>
<input
type="text"
value={store.draft.opciones[op]?.titulo ?? ""}
onChange={(e) =>
store.updateOpcionMeta(op, { titulo: e.target.value })
}
placeholder={op === "1" ? "Ej. Capacitacion y revision" : "Ej. Arquitectura completa"}
className={INPUT_CLS}
/>
<label className="block text-xs font-medium text-muted mb-1 mt-3">
Descripcion / scope
</label>
<textarea
value={store.draft.opciones[op]?.descripcion ?? ""}
onChange={(e) =>
store.updateOpcionMeta(op, { descripcion: e.target.value })
}
rows={3}
placeholder="Que incluye esta opcion..."
className={INPUT_CLS}
/>
<label className="block text-xs font-medium text-muted mb-1 mt-3">
Lo que NO incluye
</label>
<textarea
value={store.draft.opciones[op]?.noIncluye ?? ""}
onChange={(e) =>
store.updateOpcionMeta(op, { noIncluye: e.target.value })
}
rows={2}
placeholder="Exclusiones de esta opcion..."
className={INPUT_CLS}
/>
</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">
@@ -604,6 +797,8 @@ export function CotizacionForm({
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{isSelected && esDoble &&
opcionSelect(serv.id, servicioData?.opcion)}
{isSelected && (
<div className="flex items-center gap-1">
<DollarSign className="w-3.5 h-3.5 text-muted" />
@@ -669,6 +864,266 @@ export function CotizacionForm({
);
})}
<div className="bg-card-bg rounded-xl border border-border p-5 mb-4">
<div className="flex items-center justify-between mb-3">
<h3 className="font-semibold flex items-center gap-2">
<Clock className="w-4 h-4 text-primary" />
Servicios por tiempo (horas / retainer)
</h3>
<div className="flex items-center gap-2">
<button
onClick={handleAddCustom}
className="flex items-center gap-1 px-3 py-1.5 border border-primary text-primary rounded-lg text-sm font-medium hover:bg-primary-light/30"
>
<Plus className="w-4 h-4" />
Por horas
</button>
<button
onClick={handleAddRetainer}
className="flex items-center gap-1 px-3 py-1.5 border border-primary text-primary rounded-lg text-sm font-medium hover:bg-primary-light/30"
>
<Plus className="w-4 h-4" />
Retainer
</button>
</div>
</div>
{customServicios.length === 0 ? (
<p className="text-xs text-muted">
Agrega partidas cobradas por tiempo: <b>por horas</b> (horas x tarifa) o{" "}
<b>retainer</b> (importe minimo mensual + horas adicionales que se facturan
aparte). Aparecen en el resumen y en la cotizacion junto al resto de servicios.
</p>
) : (
<div className="space-y-3">
{customServicios.map((s) => (
<div
key={s.catalogoId}
className="border border-primary/40 bg-primary-light/10 rounded-lg p-3"
>
<div className="grid grid-cols-2 md:grid-cols-12 gap-2">
<div className="col-span-2 md:col-span-4">
<label className="block text-xs font-medium text-muted mb-1">
Concepto
</label>
<input
type="text"
value={s.nombre}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
nombre: e.target.value,
})
}
placeholder={
s.modeloCobro === "retainer"
? "Ej. Acompanamiento mensual"
: "Ej. Horas de consultoria"
}
className="w-full px-2 py-1.5 border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div className="md:col-span-3">
<label className="block text-xs font-medium text-muted mb-1">
Modelo
</label>
<select
value={s.modeloCobro === "retainer" ? "retainer" : "horas"}
onChange={(e) =>
handleModeloChange(s.catalogoId, e.target.value)
}
className="w-full px-2 py-1.5 border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-primary bg-white"
>
<option value="horas">Por horas</option>
<option value="retainer">Retainer</option>
</select>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-medium text-muted mb-1">
Fase
</label>
<select
value={s.fase}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
fase: parseInt(e.target.value, 10),
})
}
className="w-full px-2 py-1.5 border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-primary bg-white"
>
{[0, 1, 2, 3].map((f) => (
<option key={f} value={f}>
Fase {f}
</option>
))}
</select>
</div>
<div className="md:col-span-2">
<label className="block text-xs font-medium text-muted mb-1">
Tipo
</label>
{s.modeloCobro === "retainer" ? (
<div className="w-full px-2 py-1.5 border border-border rounded text-sm bg-gray-50 text-muted">
Mensual
</div>
) : (
<select
value={s.tipoPago}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
tipoPago: e.target.value,
})
}
className="w-full px-2 py-1.5 border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-primary bg-white"
>
<option value="unico">Pago Unico</option>
<option value="mensual">Mensual</option>
</select>
)}
</div>
<div className="md:col-span-1 flex items-end justify-end">
<button
onClick={() => store.removeServicio(s.catalogoId)}
className="p-1.5 text-muted hover:text-red-600 hover:bg-red-50 rounded"
title="Eliminar partida"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
{s.modeloCobro === "retainer" ? (
<div className="grid grid-cols-2 md:grid-cols-12 gap-2 mt-2">
<div className="md:col-span-4">
<label className="block text-xs font-medium text-muted mb-1">
Monto minimo mensual
</label>
<input
type="number"
min={0}
value={s.montoMinimo ?? 0}
onChange={(e) =>
handleRetainerMonto(
s.catalogoId,
parseFloat(e.target.value) || 0
)
}
className="w-full px-2 py-1.5 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div className="md:col-span-4">
<label className="block text-xs font-medium text-muted mb-1">
Horas incluidas
</label>
<input
type="number"
min={0}
value={s.horasIncluidas ?? 0}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
horasIncluidas: parseFloat(e.target.value) || 0,
})
}
className="w-full px-2 py-1.5 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div className="md:col-span-4">
<label className="block text-xs font-medium text-muted mb-1">
Tarifa hora adicional
</label>
<input
type="number"
min={0}
value={s.tarifaHora ?? 0}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
tarifaHora: parseFloat(e.target.value) || 0,
})
}
className="w-full px-2 py-1.5 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
</div>
) : (
<div className="grid grid-cols-2 md:grid-cols-12 gap-2 mt-2">
<div className="md:col-span-3">
<label className="block text-xs font-medium text-muted mb-1">
Horas
</label>
<input
type="number"
min={0}
value={s.horas ?? 0}
onChange={(e) =>
handleCustomHoras(
s.catalogoId,
parseFloat(e.target.value) || 0
)
}
className="w-full px-2 py-1.5 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
<div className="md:col-span-3">
<label className="block text-xs font-medium text-muted mb-1">
Tarifa/hora
</label>
<input
type="number"
min={0}
value={s.tarifaHora ?? 0}
onChange={(e) =>
handleCustomTarifa(
s.catalogoId,
parseFloat(e.target.value) || 0
)
}
className="w-full px-2 py-1.5 border border-border rounded text-sm text-right focus:outline-none focus:ring-1 focus:ring-primary"
/>
</div>
</div>
)}
<div className="flex items-center justify-between mt-2 text-sm">
<div className="flex items-center gap-2">
<span className="text-xs text-muted">Entrega:</span>
<input
type="text"
value={s.tiempoEntrega}
onChange={(e) =>
store.updateServicio(s.catalogoId, {
tiempoEntrega: e.target.value,
})
}
className="w-40 px-2 py-1 border border-border rounded text-xs focus:outline-none focus:ring-1 focus:ring-primary"
/>
{esDoble && (
<>
<span className="text-xs text-muted ml-2">Opcion:</span>
{opcionSelect(s.catalogoId, s.opcion)}
</>
)}
</div>
<span className="font-semibold">
{s.modeloCobro === "retainer" ? (
<span className="text-primary">
{describirRetainer(
s.montoMinimo ?? 0,
s.horasIncluidas ?? 0,
s.tarifaHora ?? 0
)}
</span>
) : (
<>
{(s.horas ?? 0)} h x {formatCurrency(s.tarifaHora ?? 0)} ={" "}
<span className="text-primary">
{formatCurrency(s.precio)}
</span>
</>
)}
</span>
</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)
@@ -782,6 +1237,43 @@ export function CotizacionForm({
<div className="px-5 py-4 border-b border-border bg-gray-50">
<h3 className="font-semibold">Resumen</h3>
</div>
{esDoble && (
<div className="p-5 space-y-4 border-b border-border">
{(["1", "2"] as const).map((op) => {
const t = totalesOpcion[op];
const meta = store.draft.opciones[op];
return (
<div key={op} className="border border-primary/30 rounded-lg p-3 bg-primary-light/10">
<h4 className="text-sm font-semibold text-primary">
Opcion {op}
{meta?.titulo ? `: ${meta.titulo}` : ""}
</h4>
<div className="flex justify-between text-xs mt-2">
<span>Total unico (c/IVA)</span>
<span className="font-medium">
{formatCurrency(t.totalUnico * (1 + IVA_RATE))}
</span>
</div>
<div className="flex justify-between text-xs mt-1">
<span>Total mensual (c/IVA)</span>
<span className="font-medium">
{formatCurrency(t.totalMensual * (1 + IVA_RATE))}
</span>
</div>
{t.horas > 0 && (
<div className="flex justify-between text-xs mt-1 text-muted">
<span>Horas estimadas</span>
<span>{t.horas} h</span>
</div>
)}
</div>
);
})}
<p className="text-[11px] text-muted">
Las partidas marcadas <b>Ambas</b> suman en las dos opciones.
</p>
</div>
)}
<div className="p-5 space-y-4">
<div>
<h4 className="text-xs font-medium text-muted uppercase tracking-wide mb-2">
+130 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { FileDown, FileSpreadsheet, Loader2 } from "lucide-react";
import { Eye, FileDown, FileSpreadsheet, Loader2, X } from "lucide-react";
import { useState } from "react";
function getFilenameFromHeaders(headers: Headers, fallback: string): string {
@@ -123,3 +123,132 @@ export function ExportPDFButtonDraft({ draft }: { draft: unknown }) {
</button>
);
}
function PDFPreviewModal({
url,
filename,
onClose,
}: {
url: string;
filename: string;
onClose: () => void;
}) {
return (
<div
className="fixed inset-0 z-50 flex flex-col bg-black/60"
onClick={onClose}
>
<div
className="flex items-center justify-between gap-4 px-4 py-3 bg-white border-b border-border"
onClick={(e) => e.stopPropagation()}
>
<h3 className="font-semibold text-sm truncate">{filename}</h3>
<div className="flex items-center gap-2 shrink-0">
<a
href={url}
download={filename}
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50"
>
<FileDown className="w-4 h-4 text-red-600" />
Descargar
</a>
<button
onClick={onClose}
aria-label="Cerrar previsualización"
className="p-2 border border-border rounded-lg hover:bg-gray-50"
>
<X className="w-4 h-4" />
</button>
</div>
</div>
<div className="flex-1 p-4" onClick={(e) => e.stopPropagation()}>
<iframe
src={url}
title="Previsualización del PDF"
className="w-full h-full rounded-lg bg-white border border-border"
/>
</div>
</div>
);
}
function usePDFPreview() {
const [loading, setLoading] = useState(false);
const [preview, setPreview] = useState<{ url: string; filename: string } | null>(null);
const open = async (fetcher: () => Promise<Response>, fallback: string) => {
setLoading(true);
try {
const res = await fetcher();
if (res.ok) {
const filename = getFilenameFromHeaders(res.headers, fallback);
const blob = await res.blob();
const url = window.URL.createObjectURL(blob);
setPreview({ url, filename });
} else {
alert("Error al generar la previsualización");
}
} catch {
alert("Error al generar la previsualización");
} finally {
setLoading(false);
}
};
const close = () => {
if (preview) window.URL.revokeObjectURL(preview.url);
setPreview(null);
};
return { loading, preview, open, close };
}
export function PreviewPDFButtonSaved({ cotizacionId }: { cotizacionId: string }) {
const { loading, preview, open, close } = usePDFPreview();
return (
<>
<button
onClick={() =>
open(() => fetch(`/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" /> : <Eye className="w-4 h-4 text-blue-600" />}
Previsualizar
</button>
{preview && (
<PDFPreviewModal url={preview.url} filename={preview.filename} onClose={close} />
)}
</>
);
}
export function PreviewPDFButtonDraft({ draft }: { draft: unknown }) {
const { loading, preview, open, close } = usePDFPreview();
return (
<>
<button
onClick={() =>
open(
() =>
fetch("/api/export/pdf", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 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" /> : <Eye className="w-4 h-4 text-blue-600" />}
Previsualizar
</button>
{preview && (
<PDFPreviewModal url={preview.url} filename={preview.filename} onClose={close} />
)}
</>
);
}
+60
View File
@@ -1,5 +1,65 @@
export const IVA_RATE = 0.16;
// Tarifa por hora sugerida para partidas personalizadas (Hora Centinela). El asesor puede ajustarla por partida.
export const TARIFA_HORA_DEFAULT = 700;
export function calcularPrecioHoras(horas: number, tarifaHora: number): number {
return Math.round((horas || 0) * (tarifaHora || 0) * 100) / 100;
}
// Modelos de cobro de una partida. "retainer" = importe minimo mensual fijo +
// tarifa de horas adicionales (las horas extra se facturan aparte, no suman al total).
export const MODELOS_COBRO: Record<string, string> = {
fijo: "Precio fijo",
horas: "Por horas",
retainer: "Retainer (minimo + adicionales)",
};
// Texto descriptivo de un retainer, reutilizado por UI, PDF y Excel.
export function describirRetainer(
montoMinimo: number,
horasIncluidas: number,
tarifaHora: number
): string {
const partes = [`${formatCurrency(montoMinimo || 0)}/mes`];
if (horasIncluidas) partes.push(`incluye ${horasIncluidas} hr`);
if (tarifaHora) partes.push(`adicional ${formatCurrency(tarifaHora)}/hr (se factura aparte)`);
return partes.join(" · ");
}
// Doble propuesta: cada partida puede ir en la Opcion 1, la Opcion 2 o en ambas.
// "ambas" aparece (y suma) en las dos opciones. null = cotizacion normal (sin doble propuesta).
export const OPCIONES = ["1", "2", "ambas"] as const;
export type OpcionPropuesta = (typeof OPCIONES)[number];
export interface MetaOpcion {
titulo?: string;
descripcion?: string;
noIncluye?: string;
}
// Totales de una opcion: suma las partidas de esa opcion + las marcadas "ambas".
// Respeta la regla de retainer: el total usa `precio`, no `horas x tarifa`. Las horas
// son informativas para la tabla comparativa.
export function calcularTotalesOpcion(
servicios: Array<{ opcion?: string | null; tipoPago: string; precio: number; horas?: number | null }>,
opcion: "1" | "2"
): { totalUnico: number; totalMensual: number; horas: number } {
const rel = servicios.filter((s) => s.opcion === "ambas" || s.opcion === opcion);
const totalUnico = rel
.filter((s) => s.tipoPago === "unico")
.reduce((a, s) => a + (s.precio || 0), 0);
const totalMensual = rel
.filter((s) => s.tipoPago === "mensual")
.reduce((a, s) => a + (s.precio || 0), 0);
const horas = rel.reduce((a, s) => a + (s.horas || 0), 0);
return {
totalUnico: Math.round(totalUnico * 100) / 100,
totalMensual: Math.round(totalMensual * 100) / 100,
horas: Math.round(horas * 100) / 100,
};
}
export const FASES: Record<number, string> = {
0: "FASE 0 - Auditoria / Acompanamiento",
1: "FASE 1 - Setup e Infraestructura",
+116 -12
View File
@@ -1,5 +1,5 @@
import PDFDocument from "pdfkit";
import { FASES_SHORT as FASES } from "./calculators";
import { FASES_SHORT as FASES, describirRetainer, formatCurrency, calcularTotalesOpcion, type MetaOpcion } from "./calculators";
interface ServicioPDF {
nombre: string;
@@ -8,6 +8,24 @@ interface ServicioPDF {
precio: number;
tiempoEntrega: string;
entregables: string[];
esPersonalizado?: boolean;
horas?: number;
tarifaHora?: number;
modeloCobro?: string;
montoMinimo?: number;
horasIncluidas?: number;
opcion?: string | null;
}
// Texto de desglose por modelo de cobro (horas / retainer) para la sub-linea del servicio.
function detalleModeloPDF(serv: ServicioPDF): string {
if (serv.modeloCobro === "retainer") {
return describirRetainer(serv.montoMinimo ?? 0, serv.horasIncluidas ?? 0, serv.tarifaHora ?? 0);
}
if ((serv.modeloCobro === "horas" || serv.esPersonalizado) && serv.horas && serv.tarifaHora) {
return `${serv.horas} h x ${formatCurrency(serv.tarifaHora)}/hr`;
}
return "";
}
interface CotizacionPDFData {
@@ -22,6 +40,8 @@ interface CotizacionPDFData {
proyecto: string;
esquemaPago: string;
servicios: ServicioPDF[];
esDoble?: boolean;
opcionesMetadata?: { "1"?: MetaOpcion; "2"?: MetaOpcion } | null;
planBucefaloNivel: string | null;
planBucefaloPrecio: number;
incluirBonos: boolean;
@@ -180,13 +200,15 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
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;
function drawTableHeader() {
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");
@@ -205,7 +227,8 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
y += 16;
}
const servH = 13 + (serv.entregables ? Math.ceil(serv.entregables.length / 2) * 8 : 0) + 5;
const detalleModelo = detalleModeloPDF(serv);
const servH = 13 + (detalleModelo ? 9 : 0) + (serv.entregables ? Math.ceil(serv.entregables.length / 2) * 8 : 0) + 5;
y = need(servH, y);
doc.font("Helvetica").fontSize(8).fillColor(DARK);
@@ -217,6 +240,12 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
doc.text(fmt(serv.precio), colPrecio, y, { width: 60, align: "right" });
y += 13;
if (detalleModelo) {
doc.font("Helvetica-Oblique").fontSize(6.5).fillColor(MUTED);
doc.text(detalleModelo, colNombre + 10, y, { width: colTipo - colNombre - 20 });
y += 9;
}
if (serv.entregables && serv.entregables.length > 0) {
const col1X = colNombre + 10;
const col2X = colNombre + W * 0.48;
@@ -251,8 +280,84 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
return y;
}
if (unicos.length > 0) y = drawSection(unicos, "Unico", "Total Pago Unico");
if (mensuales.length > 0) y = drawSection(mensuales, "Mensual", "Total Pago Mensual");
// Encabezado de una opcion (titulo, descripcion, exclusiones) en doble propuesta.
function drawOpcionHeader(op: "1" | "2") {
const meta = data.opcionesMetadata?.[op] || {};
y = need(30, y);
y += 4;
doc.rect(L, y, W, 18).fill(PRIMARY);
doc.font("Helvetica-Bold").fontSize(10).fillColor(WHITE)
.text(`OPCION ${op}${meta.titulo ? ": " + meta.titulo : ""}`, L + 8, y + 4, { width: W - 16 });
y += 22;
if (meta.descripcion) {
const h = txtHeight(meta.descripcion, W - 12, 7.5);
y = need(h + 4, y);
doc.font("Helvetica").fontSize(7.5).fillColor(DARK).text(meta.descripcion, L + 6, y, { width: W - 12 });
y += h + 4;
}
if (meta.noIncluye) {
const label = `No incluye: ${meta.noIncluye}`;
const h = txtHeight(label, W - 12, 7);
y = need(h + 4, y);
doc.font("Helvetica-Oblique").fontSize(7).fillColor(MUTED).text(label, L + 6, y, { width: W - 12 });
y += h + 6;
}
}
// Tabla comparativa final: totales (con IVA) y horas por opcion.
function drawComparativa() {
const t1 = calcularTotalesOpcion(data.servicios, "1");
const t2 = calcularTotalesOpcion(data.servicios, "2");
y = need(90, y);
y += 6;
doc.rect(L, y, 3, 10).fill(PRIMARY);
doc.font("Helvetica-Bold").fontSize(10).fillColor(DARK).text("Comparativa de opciones", L + 10, y);
y += 18;
const cLabel = L;
const cOp1 = L + W * 0.45;
const cOp2 = L + W * 0.72;
const t1Tit = data.opcionesMetadata?.["1"]?.titulo;
const t2Tit = data.opcionesMetadata?.["2"]?.titulo;
rowBg(y, 16, LIGHT_BG);
doc.font("Helvetica-Bold").fontSize(7.5).fillColor(DARK);
doc.text("Concepto", cLabel + 6, y + 4);
doc.text(`Opcion 1${t1Tit ? " - " + t1Tit : ""}`, cOp1, y + 4, { width: W * 0.27 - 4 });
doc.text(`Opcion 2${t2Tit ? " - " + t2Tit : ""}`, cOp2, y + 4, { width: W * 0.28 - 4 });
y += 18;
const filas: [string, string, string][] = [
["Total unico (c/IVA)", fmt(t1.totalUnico * 1.16), fmt(t2.totalUnico * 1.16)],
["Total mensual (c/IVA)", fmt(t1.totalMensual * 1.16), fmt(t2.totalMensual * 1.16)],
["Horas estimadas", `${t1.horas} h`, `${t2.horas} h`],
];
for (const [lab, v1, v2] of filas) {
y = need(14, y);
doc.font("Helvetica").fontSize(8).fillColor(DARK).text(lab, cLabel + 6, y);
doc.font("Helvetica-Bold").fontSize(8).fillColor(DARK).text(v1, cOp1, y, { width: W * 0.27 - 4 });
doc.text(v2, cOp2, y, { width: W * 0.28 - 4 });
doc.save();
doc.moveTo(cLabel + 6, y + 12).lineTo(L + W, y + 12).strokeColor("#e5e7eb").lineWidth(0.2).stroke();
doc.restore();
y += 14;
}
y += 8;
}
if (data.esDoble) {
for (const op of ["1", "2"] as const) {
const inOp = (s: ServicioPDF) => s.opcion === op || s.opcion === "ambas";
drawOpcionHeader(op);
drawTableHeader();
const u = unicos.filter(inOp);
const me = mensuales.filter(inOp);
if (u.length > 0) y = drawSection(u, "Unico", `Total Pago Unico - Opcion ${op}`);
if (me.length > 0) y = drawSection(me, "Mensual", `Total Pago Mensual - Opcion ${op}`);
}
drawComparativa();
} else {
drawTableHeader();
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);
@@ -350,7 +455,6 @@ export async function generateCotizacionPDF(data: CotizacionPDFData): Promise<Bu
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";
+23
View File
@@ -8,8 +8,26 @@ const servicioSchema = z.object({
precio: z.number().min(0),
tiempoEntrega: z.string().min(1),
entregables: z.array(z.string()),
esPersonalizado: z.boolean().optional(),
horas: z.number().min(0).optional(),
tarifaHora: z.number().min(0).optional(),
modeloCobro: z.enum(["fijo", "horas", "retainer"]).optional(),
montoMinimo: z.number().min(0).optional(),
horasIncluidas: z.number().min(0).optional(),
opcion: z.enum(["1", "2", "ambas"]).optional(),
});
const metaOpcionSchema = z.object({
titulo: z.string().optional(),
descripcion: z.string().optional(),
noIncluye: z.string().optional(),
});
// { "1": { titulo, descripcion, noIncluye }, "2": {...} }
const opcionesSchema = z
.object({ "1": metaOpcionSchema.optional(), "2": metaOpcionSchema.optional() })
.optional();
export const cotizacionPostSchema = z.object({
numero: z.string().min(1),
fecha: z.coerce.date(),
@@ -20,6 +38,8 @@ export const cotizacionPostSchema = z.object({
esquemaPago: z.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual"]),
incluirBonos: z.boolean(),
incluirFinanciamiento: z.boolean(),
esDoble: z.boolean().optional(),
opciones: opcionesSchema,
observaciones: z.string(),
asesorId: z.string().min(1),
cliente: z.object({
@@ -46,6 +66,8 @@ export const cotizacionPutSchema = z.object({
esquemaPago: z.enum(["Pago Unico", "Mensual", "Pago Unico/Mensual"]),
incluirBonos: z.boolean(),
incluirFinanciamiento: z.boolean(),
esDoble: z.boolean().optional(),
opciones: opcionesSchema,
observaciones: z.string(),
cliente: z.object({
nombre: z.string().min(1, "Cliente nombre es requerido"),
@@ -77,6 +99,7 @@ export const servicioCatalogoSchema = z.object({
entregablesDefault: z.array(z.string()),
categoriaId: z.string().min(1, "Categoria es requerida"),
variante: z.string().nullable(),
nivel: z.string().nullable().optional(),
orden: z.number().int().min(0),
});
+30
View File
@@ -1,4 +1,5 @@
import { create } from "zustand";
import type { MetaOpcion } from "./calculators";
export interface ServicioSeleccionado {
catalogoId: string;
@@ -9,6 +10,18 @@ export interface ServicioSeleccionado {
tiempoEntrega: string;
entregables: string[];
notas?: string;
// Doble propuesta: "1" | "2" | "ambas". undefined = cotizacion normal.
opcion?: string;
// Partidas personalizadas (sin catalogo). modeloCobro define como se calcula el precio:
// - "fijo": precio editable / precioBase (servicios de catalogo)
// - "horas": precio = horas * tarifaHora
// - "retainer": precio = montoMinimo (mensual); tarifaHora y horasIncluidas son informativos
esPersonalizado?: boolean;
horas?: number;
tarifaHora?: number;
modeloCobro?: string;
montoMinimo?: number;
horasIncluidas?: number;
}
export interface CotizacionDraft {
@@ -29,6 +42,9 @@ export interface CotizacionDraft {
planBucefaloNivel: string | null;
servicios: ServicioSeleccionado[];
observaciones: string;
// Doble propuesta: dos opciones comparables dentro de una misma cotizacion.
esDoble: boolean;
opciones: { "1"?: MetaOpcion; "2"?: MetaOpcion };
}
interface CotizacionStore {
@@ -41,6 +57,7 @@ interface CotizacionStore {
updateServicio: (catalogoId: string, updates: Partial<ServicioSeleccionado>) => void;
removeServicio: (catalogoId: string) => void;
setServicios: (servicios: ServicioSeleccionado[]) => void;
updateOpcionMeta: (opcion: "1" | "2", parcial: Partial<MetaOpcion>) => void;
resetDraft: () => void;
}
@@ -62,6 +79,8 @@ const initialDraft: CotizacionDraft = {
planBucefaloNivel: null,
servicios: [],
observaciones: "",
esDoble: false,
opciones: {},
};
export const useCotizacionStore = create<CotizacionStore>((set) => ({
@@ -116,5 +135,16 @@ export const useCotizacionStore = create<CotizacionStore>((set) => ({
setServicios: (servicios) =>
set((state) => ({ draft: { ...state.draft, servicios } })),
updateOpcionMeta: (opcion, parcial) =>
set((state) => ({
draft: {
...state.draft,
opciones: {
...state.draft.opciones,
[opcion]: { ...state.draft.opciones[opcion], ...parcial },
},
},
})),
resetDraft: () => set({ draft: { ...initialDraft } }),
}));