feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
|
||||
import { AuthProvider, useAuth } from "@/lib/auth";
|
||||
import { DialogProvider } from "@/components/ui/DialogProvider";
|
||||
import { LoadingScreen } from "@/components/ui/LoadingScreen";
|
||||
import Sidebar from "@/components/layout/Sidebar";
|
||||
import LoginPage from "@/pages/LoginPage";
|
||||
import AprobarTokenPage from "@/pages/AprobarTokenPage";
|
||||
import { DashboardPage } from "@/pages/app/DashboardPage";
|
||||
import { CotizacionesPage } from "@/pages/app/cotizaciones/CotizacionesPage";
|
||||
import { NuevaCotizacionPage } from "@/pages/app/cotizaciones/NuevaCotizacionPage";
|
||||
import { CotizacionDetailPage } from "@/pages/app/cotizaciones/CotizacionDetailPage";
|
||||
import { EditarCotizacionPage } from "@/pages/app/cotizaciones/EditarCotizacionPage";
|
||||
import { ClientesPage } from "@/pages/app/ClientesPage";
|
||||
import { CatalogoPage } from "@/pages/app/CatalogoPage";
|
||||
import { CobrosPage } from "@/pages/app/cobros/CobrosPage";
|
||||
import { ConfiguracionPage } from "@/pages/app/ConfiguracionPage";
|
||||
import { ClienteShell } from "@/pages/cliente/ClienteShell";
|
||||
import { ClienteInicioPage } from "@/pages/cliente/ClienteInicioPage";
|
||||
import { ClienteCotizacionesPage } from "@/pages/cliente/ClienteCotizacionesPage";
|
||||
import { ClienteCotizacionDetallePage } from "@/pages/cliente/ClienteCotizacionDetallePage";
|
||||
import { ClientePagosPage } from "@/pages/cliente/ClientePagosPage";
|
||||
|
||||
function StaffGuardLayout() {
|
||||
const { user, loading } = useAuth();
|
||||
if (loading) return <LoadingScreen label="Verificando sesión..." />;
|
||||
if (!user) return <Navigate to="/login" replace />;
|
||||
if (user.role === "cliente") return <Navigate to="/cliente" replace />;
|
||||
|
||||
return (
|
||||
<DialogProvider>
|
||||
<div className="min-h-screen flex bg-background">
|
||||
<Sidebar />
|
||||
<main className="flex-1 lg:ml-64">
|
||||
<div className="p-4 lg:p-8 pt-16 lg:pt-8">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</DialogProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ClienteGuardLayout() {
|
||||
const { user, loading } = useAuth();
|
||||
if (loading) return <LoadingScreen label="Verificando sesión..." />;
|
||||
if (!user) return <Navigate to="/login?panel=cliente" replace />;
|
||||
if (user.role !== "cliente") return <Navigate to="/" replace />;
|
||||
|
||||
return (
|
||||
<DialogProvider>
|
||||
<div className="min-h-screen bg-background">
|
||||
<ClienteShell nombre={user.clienteNombre || user.name} />
|
||||
<main className="mx-auto w-full max-w-5xl px-4 lg:px-8 py-6 lg:py-8">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</DialogProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/aprobar/:token" element={<AprobarTokenPage />} />
|
||||
|
||||
<Route element={<StaffGuardLayout />}>
|
||||
<Route path="/" element={<DashboardPage />} />
|
||||
<Route path="/cotizaciones" element={<CotizacionesPage />} />
|
||||
<Route path="/cotizaciones/nueva" element={<NuevaCotizacionPage />} />
|
||||
<Route path="/cotizaciones/:id" element={<CotizacionDetailPage />} />
|
||||
<Route path="/cotizaciones/:id/editar" element={<EditarCotizacionPage />} />
|
||||
<Route path="/clientes" element={<ClientesPage />} />
|
||||
<Route path="/catalogo" element={<CatalogoPage />} />
|
||||
<Route path="/cobros" element={<CobrosPage />} />
|
||||
<Route path="/configuracion" element={<ConfiguracionPage />} />
|
||||
</Route>
|
||||
|
||||
<Route path="/cliente" element={<ClienteGuardLayout />}>
|
||||
<Route index element={<ClienteInicioPage />} />
|
||||
<Route path="cotizaciones" element={<ClienteCotizacionesPage />} />
|
||||
<Route path="cotizaciones/:id" element={<ClienteCotizacionDetallePage />} />
|
||||
<Route path="pagos" element={<ClientePagosPage />} />
|
||||
</Route>
|
||||
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
const COLORS: Record<string, string> = {
|
||||
borrador: "bg-gray-100 text-gray-700",
|
||||
aprobada: "bg-indigo-100 text-indigo-800",
|
||||
enviada: "bg-blue-100 text-blue-700",
|
||||
aceptada: "bg-green-100 text-green-700",
|
||||
rechazada: "bg-red-100 text-red-700",
|
||||
vencida: "bg-amber-100 text-amber-800",
|
||||
};
|
||||
|
||||
const LABELS: Record<string, string> = {
|
||||
borrador: "Borrador",
|
||||
aprobada: "Aprobada",
|
||||
enviada: "Enviada",
|
||||
aceptada: "Aceptada",
|
||||
rechazada: "Rechazada",
|
||||
vencida: "Vencida",
|
||||
};
|
||||
|
||||
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
|
||||
}`}
|
||||
>
|
||||
{LABELS[estado] || estado.charAt(0).toUpperCase() + estado.slice(1)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
"use client";
|
||||
|
||||
import { Eye, FileDown, FileSpreadsheet, Loader2, X } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
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 showToast = useToast();
|
||||
|
||||
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 {
|
||||
showToast("Error al exportar", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al exportar", "error");
|
||||
} 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 {
|
||||
showToast("Error al exportar", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al exportar", "error");
|
||||
} 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>
|
||||
);
|
||||
}
|
||||
|
||||
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 showToast = useToast();
|
||||
|
||||
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 {
|
||||
showToast("Error al generar la previsualización", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al generar la previsualización", "error");
|
||||
} 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} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Sparkles, Download, Save, AlertTriangle, Info, Lock, RefreshCw, ChevronDown, ChevronRight } from "lucide-react";
|
||||
import { useToast, useConfirm } from "@/components/ui/DialogProvider";
|
||||
|
||||
// Panel de la propuesta consultiva: generar, revisar, editar y descargar.
|
||||
//
|
||||
// Regla de diseno deliberada: los avisos van ARRIBA de los botones de descarga.
|
||||
// El objetivo es que revisar sea mas facil que aprobar, no al reves.
|
||||
|
||||
type Confianza = "confirmado" | "estimado" | "por_validar";
|
||||
type Urgencia = "rojo" | "ambar" | "azul" | "verde";
|
||||
|
||||
interface Aviso {
|
||||
regla: string;
|
||||
severidad: "bloqueante" | "advertencia";
|
||||
mensaje: string;
|
||||
ruta?: string;
|
||||
}
|
||||
|
||||
interface Propuesta {
|
||||
hechos: {
|
||||
citas: { id: string; textoLiteral: string; quienLoDijo: string }[];
|
||||
hechos: { id: string; enunciado: string; confianza: Confianza; citas: string[] }[];
|
||||
materialesPendientes: { texto: string; bloqueaEntrega: boolean }[];
|
||||
decisionesPendientes: { texto: string; quienDecide: string }[];
|
||||
mencionesFueraDeAlcance: string[];
|
||||
redFlags: { senal: string; severidad: string }[];
|
||||
};
|
||||
diagnostico: {
|
||||
hallazgos: { id: string; urgencia: Urgencia; titulo: string; descripcion: string; confianza: Confianza; citas: string[]; hechos: string[] }[];
|
||||
valorProblema: {
|
||||
dimensiones: { tipo: string; descripcion: string; calculo: { factores: { nombre: string; valor: number }[]; montoAnualMXN: number | null }; confianza: Confianza; hechos: string[] }[];
|
||||
notaMetodologia: string;
|
||||
};
|
||||
resultados: { enunciado: string; metrica: string; lineaBase: string | null; periodoMedicion: string }[];
|
||||
};
|
||||
redaccion: {
|
||||
hero: { titulo: string; subtitulo: string };
|
||||
citaDestacadaId: string;
|
||||
alcance: { refPartida: string; descripcionResultado: string }[];
|
||||
beneficios: { etiqueta: string; texto: string; hallazgoId: string }[];
|
||||
exclusiones: { texto: string; razon: string }[];
|
||||
backlogEvolucion: { problema: string; momentoSugerido: string }[];
|
||||
notasInternas: string[];
|
||||
};
|
||||
}
|
||||
|
||||
const COLOR_URGENCIA: Record<Urgencia, string> = {
|
||||
rojo: "bg-red-500",
|
||||
ambar: "bg-amber-500",
|
||||
azul: "bg-blue-500",
|
||||
verde: "bg-green-500",
|
||||
};
|
||||
const ETIQUETA_URGENCIA: Record<Urgencia, string> = {
|
||||
rojo: "Problema critico",
|
||||
ambar: "Area de mejora",
|
||||
azul: "Oportunidad",
|
||||
verde: "Ventaja existente",
|
||||
};
|
||||
|
||||
const INPUT = "w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-1 focus:ring-primary";
|
||||
|
||||
export default function PropuestaIAPanel({ cotizacionId }: { cotizacionId: string; numero?: string }) {
|
||||
const toast = useToast();
|
||||
const confirm = useConfirm();
|
||||
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const [cargando, setCargando] = useState(true);
|
||||
const [generando, setGenerando] = useState(false);
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
const [transcripcion, setTranscripcion] = useState("");
|
||||
const [propuesta, setPropuesta] = useState<Propuesta | null>(null);
|
||||
const [avisos, setAvisos] = useState<Aviso[]>([]);
|
||||
const [editada, setEditada] = useState(false);
|
||||
const [sucio, setSucio] = useState(false);
|
||||
|
||||
const cargar = useCallback(async () => {
|
||||
try {
|
||||
const r = await fetch(`/api/propuesta-ia/${cotizacionId}`);
|
||||
const d = await r.json();
|
||||
if (d.propuesta) {
|
||||
setPropuesta(d.propuesta);
|
||||
setAvisos(Array.isArray(d.avisos) ? d.avisos : []);
|
||||
setEditada(Boolean(d.editada));
|
||||
setAbierto(true);
|
||||
}
|
||||
} finally {
|
||||
setCargando(false);
|
||||
}
|
||||
}, [cotizacionId]);
|
||||
|
||||
useEffect(() => {
|
||||
void cargar();
|
||||
}, [cargar]);
|
||||
|
||||
async function generar() {
|
||||
if (propuesta) {
|
||||
const ok = await confirm({
|
||||
title: "Regenerar la propuesta",
|
||||
message: "Se generara una propuesta nueva. La version actual y tus ediciones quedaran reemplazadas.",
|
||||
confirmText: "Regenerar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
}
|
||||
setGenerando(true);
|
||||
try {
|
||||
const r = await fetch(`/api/propuesta-ia/${cotizacionId}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ transcripcion }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (!r.ok) {
|
||||
toast(d.error || "No se pudo generar la propuesta", "error");
|
||||
return;
|
||||
}
|
||||
setPropuesta(d.propuesta);
|
||||
setAvisos(Array.isArray(d.avisos) ? d.avisos : []);
|
||||
setEditada(false);
|
||||
setSucio(false);
|
||||
setAbierto(true);
|
||||
const bloqueantes = (d.avisos as Aviso[]).filter((a) => a.severidad === "bloqueante").length;
|
||||
toast(
|
||||
bloqueantes > 0
|
||||
? `Propuesta generada con ${bloqueantes} aviso(s) que debes resolver antes de enviarla.`
|
||||
: "Propuesta generada. Revisala antes de enviarla.",
|
||||
bloqueantes > 0 ? "error" : "success"
|
||||
);
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : "Error al generar", "error");
|
||||
} finally {
|
||||
setGenerando(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function guardar() {
|
||||
if (!propuesta) return;
|
||||
setGuardando(true);
|
||||
try {
|
||||
const r = await fetch(`/api/propuesta-ia/${cotizacionId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ propuesta }),
|
||||
});
|
||||
const d = await r.json();
|
||||
if (!r.ok) {
|
||||
toast(typeof d.error === "string" ? d.error : "No se pudo guardar", "error");
|
||||
return;
|
||||
}
|
||||
setAvisos(Array.isArray(d.avisos) ? d.avisos : []);
|
||||
setEditada(true);
|
||||
setSucio(false);
|
||||
toast("Cambios guardados y revalidados.", "success");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Aplica un cambio al objeto y marca el panel como sucio. */
|
||||
function editar(fn: (p: Propuesta) => void) {
|
||||
setPropuesta((prev) => {
|
||||
if (!prev) return prev;
|
||||
const copia = structuredClone(prev) as Propuesta;
|
||||
fn(copia);
|
||||
return copia;
|
||||
});
|
||||
setSucio(true);
|
||||
}
|
||||
|
||||
const bloqueantes = avisos.filter((a) => a.severidad === "bloqueante");
|
||||
const advertencias = avisos.filter((a) => a.severidad === "advertencia");
|
||||
const citaDestacada = propuesta?.hechos.citas.find((c) => c.id === propuesta.redaccion.citaDestacadaId);
|
||||
|
||||
if (cargando) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5">
|
||||
<p className="text-sm text-muted">Cargando propuesta consultiva...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<button
|
||||
onClick={() => setAbierto((v) => !v)}
|
||||
className="w-full flex items-center justify-between px-5 py-4 hover:bg-gray-50"
|
||||
>
|
||||
<span className="flex items-center gap-2 font-semibold">
|
||||
<Sparkles className="w-4 h-4 text-primary" />
|
||||
Propuesta consultiva con IA
|
||||
{editada && (
|
||||
<span className="text-[11px] font-medium px-2 py-0.5 rounded-full bg-primary-light text-primary">
|
||||
editada por ti
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{abierto ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
|
||||
</button>
|
||||
|
||||
{abierto && (
|
||||
<div className="px-5 pb-5 space-y-5 border-t border-border pt-5">
|
||||
{/* ── Entrada ── */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-1">Transcripcion de la reunion (opcional)</label>
|
||||
<p className="text-xs text-muted mb-2">
|
||||
Pega aqui lo que se dijo en la reunion de discovery. Sin transcripcion, la IA trabaja
|
||||
solo con las observaciones y notas de la cotizacion, y marcara mas cosas por validar.
|
||||
</p>
|
||||
<textarea
|
||||
value={transcripcion}
|
||||
onChange={(e) => setTranscripcion(e.target.value)}
|
||||
rows={4}
|
||||
placeholder="Pega la transcripcion..."
|
||||
className={INPUT}
|
||||
/>
|
||||
<button
|
||||
onClick={generar}
|
||||
disabled={generando}
|
||||
className="mt-3 flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{generando ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
|
||||
{generando ? "Generando (tarda un par de minutos)..." : propuesta ? "Regenerar" : "Generar propuesta"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{propuesta && (
|
||||
<>
|
||||
{/* ── Avisos: van ARRIBA de las descargas a proposito ── */}
|
||||
{bloqueantes.length > 0 && (
|
||||
<div className="rounded-lg border border-red-300 bg-red-50 p-4">
|
||||
<p className="flex items-center gap-2 text-sm font-semibold text-red-800 mb-2">
|
||||
<AlertTriangle className="w-4 h-4" />
|
||||
{bloqueantes.length} aviso(s) que debes resolver antes de enviar
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{bloqueantes.map((a, i) => (
|
||||
<li key={i} className="text-xs text-red-800">
|
||||
<span className="font-mono font-semibold">{a.regla}</span>
|
||||
{a.ruta && <span className="text-red-600"> · {a.ruta}</span>} — {a.mensaje}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{advertencias.length > 0 && (
|
||||
<div className="rounded-lg border border-amber-300 bg-amber-50 p-4">
|
||||
<p className="flex items-center gap-2 text-sm font-semibold text-amber-900 mb-2">
|
||||
<Info className="w-4 h-4" />
|
||||
{advertencias.length} cosa(s) que conviene revisar
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{advertencias.map((a, i) => (
|
||||
<li key={i} className="text-xs text-amber-900">
|
||||
<span className="font-mono font-semibold">{a.regla}</span>
|
||||
{a.ruta && <span className="opacity-70"> · {a.ruta}</span>} — {a.mensaje}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{avisos.length === 0 && (
|
||||
<div className="rounded-lg border border-green-300 bg-green-50 p-3">
|
||||
<p className="text-sm text-green-800">Sin avisos de validacion. Revisa el contenido de todas formas.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Edicion ── */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-1">Titulo</label>
|
||||
<input
|
||||
value={propuesta.redaccion.hero.titulo}
|
||||
onChange={(e) => editar((p) => { p.redaccion.hero.titulo = e.target.value; })}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-1">Subtitulo</label>
|
||||
<textarea
|
||||
value={propuesta.redaccion.hero.subtitulo}
|
||||
onChange={(e) => editar((p) => { p.redaccion.hero.subtitulo = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Hallazgos del diagnostico
|
||||
</label>
|
||||
<div className="space-y-3">
|
||||
{propuesta.diagnostico.hallazgos.map((h, i) => (
|
||||
<div key={h.id} className="border border-border rounded-lg p-3">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<span className={`w-2.5 h-2.5 rounded-full ${COLOR_URGENCIA[h.urgencia]}`} />
|
||||
<span className="text-[11px] text-muted">
|
||||
{ETIQUETA_URGENCIA[h.urgencia]} · {h.confianza.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
value={h.titulo}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.hallazgos[i].titulo = e.target.value; })}
|
||||
className={`${INPUT} mb-2 font-medium`}
|
||||
/>
|
||||
<textarea
|
||||
value={h.descripcion}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.hallazgos[i].descripcion = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Alcance (la descripcion; los precios los pone el sistema)
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.redaccion.alcance.map((a, i) => (
|
||||
<div key={a.refPartida} className="flex gap-2 items-start">
|
||||
<span className="text-xs font-mono text-muted mt-2.5 shrink-0">{a.refPartida}</span>
|
||||
<textarea
|
||||
value={a.descripcionResultado}
|
||||
onChange={(e) => editar((p) => { p.redaccion.alcance[i].descripcionResultado = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">Exclusiones</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.redaccion.exclusiones.map((ex, i) => (
|
||||
<textarea
|
||||
key={i}
|
||||
value={ex.texto}
|
||||
onChange={(e) => editar((p) => { p.redaccion.exclusiones[i].texto = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Por que tiene sentido
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.redaccion.beneficios.map((b, i) => (
|
||||
<div key={i} className="flex gap-2 items-start">
|
||||
<input
|
||||
value={b.etiqueta}
|
||||
onChange={(e) => editar((p) => { p.redaccion.beneficios[i].etiqueta = e.target.value; })}
|
||||
className={`${INPUT} max-w-[9rem] shrink-0`}
|
||||
/>
|
||||
<textarea
|
||||
value={b.texto}
|
||||
onChange={(e) => editar((p) => { p.redaccion.beneficios[i].texto = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Los grupos de abajo tambien se imprimen al cliente, asi que tambien
|
||||
pueden disparar un aviso bloqueante. Si no fueran editables, un
|
||||
bloqueante ahi no tendria mas salida que regenerar la propuesta. */}
|
||||
|
||||
{citaDestacada && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-1">
|
||||
Cita destacada
|
||||
</label>
|
||||
<p className="text-xs text-muted mb-2">
|
||||
Se imprime literal. Editala solo para quitar un dato sensible, nunca para
|
||||
mejorarle la redaccion al cliente.
|
||||
</p>
|
||||
<textarea
|
||||
value={citaDestacada.textoLiteral}
|
||||
onChange={(e) =>
|
||||
editar((p) => {
|
||||
const c = p.hechos.citas.find((x) => x.id === p.redaccion.citaDestacadaId);
|
||||
if (c) c.textoLiteral = e.target.value;
|
||||
})
|
||||
}
|
||||
rows={2}
|
||||
className={`${INPUT} mb-2`}
|
||||
/>
|
||||
<input
|
||||
value={citaDestacada.quienLoDijo}
|
||||
onChange={(e) =>
|
||||
editar((p) => {
|
||||
const c = p.hechos.citas.find((x) => x.id === p.redaccion.citaDestacadaId);
|
||||
if (c) c.quienLoDijo = e.target.value;
|
||||
})
|
||||
}
|
||||
placeholder="Quien lo dijo (usa el rol, no el nombre)"
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{propuesta.diagnostico.valorProblema.dimensiones.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Lo que cuesta no resolverlo
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.diagnostico.valorProblema.dimensiones.map((dim, i) => (
|
||||
<div key={i} className="flex gap-2 items-start">
|
||||
<span className="text-xs text-muted mt-2.5 shrink-0 w-20">{dim.tipo}</span>
|
||||
<textarea
|
||||
value={dim.descripcion}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.valorProblema.dimensiones[i].descripcion = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
value={propuesta.diagnostico.valorProblema.notaMetodologia}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.valorProblema.notaMetodologia = e.target.value; })}
|
||||
rows={2}
|
||||
placeholder="Nota de metodologia"
|
||||
className={`${INPUT} mt-2`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{propuesta.diagnostico.resultados.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Resultados a lograr
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.diagnostico.resultados.map((r, i) => (
|
||||
<div key={i} className="space-y-1">
|
||||
<textarea
|
||||
value={r.enunciado}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.resultados[i].enunciado = e.target.value; })}
|
||||
rows={2}
|
||||
className={INPUT}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={r.metrica}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.resultados[i].metrica = e.target.value; })}
|
||||
placeholder="Metrica"
|
||||
className={INPUT}
|
||||
/>
|
||||
<input
|
||||
value={r.periodoMedicion}
|
||||
onChange={(e) => editar((p) => { p.diagnostico.resultados[i].periodoMedicion = e.target.value; })}
|
||||
placeholder="Periodo"
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(propuesta.hechos.materialesPendientes.length > 0 ||
|
||||
propuesta.hechos.decisionesPendientes.length > 0) && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Que necesitamos de ustedes
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.hechos.materialesPendientes.map((m, i) => (
|
||||
<input
|
||||
key={`mat-${i}`}
|
||||
value={m.texto}
|
||||
onChange={(e) => editar((p) => { p.hechos.materialesPendientes[i].texto = e.target.value; })}
|
||||
className={INPUT}
|
||||
/>
|
||||
))}
|
||||
{propuesta.hechos.decisionesPendientes.map((dd, i) => (
|
||||
<div key={`dec-${i}`} className="flex gap-2">
|
||||
<textarea
|
||||
value={dd.texto}
|
||||
onChange={(e) => editar((p) => { p.hechos.decisionesPendientes[i].texto = e.target.value; })}
|
||||
rows={1}
|
||||
className={INPUT}
|
||||
/>
|
||||
<input
|
||||
value={dd.quienDecide}
|
||||
onChange={(e) => editar((p) => { p.hechos.decisionesPendientes[i].quienDecide = e.target.value; })}
|
||||
placeholder="Quien decide"
|
||||
className={`${INPUT} max-w-[11rem] shrink-0`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{propuesta.redaccion.backlogEvolucion.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-xs font-semibold uppercase tracking-wide text-muted mb-2">
|
||||
Registrado para mas adelante
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
{propuesta.redaccion.backlogEvolucion.map((b, i) => (
|
||||
<div key={i} className="flex gap-2">
|
||||
<textarea
|
||||
value={b.problema}
|
||||
onChange={(e) => editar((p) => { p.redaccion.backlogEvolucion[i].problema = e.target.value; })}
|
||||
rows={1}
|
||||
className={INPUT}
|
||||
/>
|
||||
<input
|
||||
value={b.momentoSugerido}
|
||||
onChange={(e) => editar((p) => { p.redaccion.backlogEvolucion[i].momentoSugerido = e.target.value; })}
|
||||
placeholder="Cuando"
|
||||
className={`${INPUT} max-w-[11rem] shrink-0`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 pt-2 border-t border-border">
|
||||
<button
|
||||
onClick={guardar}
|
||||
disabled={!sucio || guardando}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-40"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
{guardando ? "Guardando..." : sucio ? "Guardar cambios" : "Sin cambios"}
|
||||
</button>
|
||||
|
||||
{/* El servidor devuelve 409 si hay bloqueantes; aqui se refleja para no
|
||||
invitar a un clic que va a fallar. La descarga del anexo interno
|
||||
sigue disponible: es la que ayuda a entender que corregir. */}
|
||||
{bloqueantes.length > 0 ? (
|
||||
<span
|
||||
className="flex items-center gap-2 px-4 py-2 border border-border rounded-lg text-sm text-muted bg-gray-50 cursor-not-allowed"
|
||||
title="Resuelve los avisos bloqueantes y guarda para habilitar la descarga"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Propuesta consultiva (PDF) — bloqueada
|
||||
</span>
|
||||
) : (
|
||||
<a
|
||||
href={`/api/propuesta-ia/${cotizacionId}/pdf`}
|
||||
className="flex items-center gap-2 px-4 py-2 border border-border rounded-lg text-sm hover:bg-gray-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Propuesta consultiva (PDF)
|
||||
</a>
|
||||
)}
|
||||
|
||||
<a
|
||||
href={`/api/propuesta-ia/${cotizacionId}/pdf?anexo=1`}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm border border-red-300 bg-red-50 text-red-800 hover:bg-red-100"
|
||||
title="Contiene ponderacion, red flags y notas internas"
|
||||
>
|
||||
<Lock className="w-4 h-4" />
|
||||
Anexo interno — NO ENVIAR
|
||||
</a>
|
||||
|
||||
{sucio && (
|
||||
<span className="text-xs text-amber-700">
|
||||
Tienes cambios sin guardar. El PDF se genera con lo ultimo guardado.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Loader2, Save, X, Info } from "lucide-react";
|
||||
import { FASES } from "@/lib/calculators";
|
||||
|
||||
// Servicio del catalogo tal como lo devuelve /api/catalogo (ver serializarServicio).
|
||||
export interface ServicioCatalogoDatos {
|
||||
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;
|
||||
nivel: string | null;
|
||||
activo: boolean;
|
||||
soloAdmin?: boolean;
|
||||
orden: number;
|
||||
enCotizaciones?: number;
|
||||
}
|
||||
|
||||
export interface CategoriaOpcion {
|
||||
id: string;
|
||||
nombre: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
const NIVELES = ["Emprendedor", "PYME", "Empresario", "Corporativo"];
|
||||
|
||||
const INPUT =
|
||||
"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";
|
||||
|
||||
interface Props {
|
||||
// null = alta; con servicio = edicion.
|
||||
servicio: Partial<ServicioCatalogoDatos> & { id?: string } | null;
|
||||
// Si no se pasan, el modal las pide a /api/categorias.
|
||||
categorias?: CategoriaOpcion[];
|
||||
// Fase preseleccionada en un alta.
|
||||
faseInicial?: number;
|
||||
// Texto de ayuda arriba del formulario (ej. el alcance de la edicion).
|
||||
aviso?: string;
|
||||
// Texto del boton en un alta (ej. "Crear y agregar").
|
||||
textoCrear?: string;
|
||||
// Mostrar Orden/Activo (en el cotizador se omiten: el orden se asigna solo).
|
||||
avanzado?: boolean;
|
||||
onSaved: (servicio: ServicioCatalogoDatos) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
// Alta y edicion de un servicio del catalogo. Hace el POST/PATCH a
|
||||
// /api/catalogo y muestra el error de la API sin cerrarse si algo falla.
|
||||
export function ServicioFormModal({
|
||||
servicio,
|
||||
categorias: categoriasProp,
|
||||
faseInicial,
|
||||
aviso,
|
||||
textoCrear = "Crear servicio",
|
||||
avanzado = true,
|
||||
onSaved,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const editando = !!servicio?.id;
|
||||
const [categorias, setCategorias] = useState<CategoriaOpcion[]>(categoriasProp ?? []);
|
||||
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 || "",
|
||||
nivel: servicio?.nivel || "",
|
||||
fase: servicio?.fase ?? faseInicial ?? 1,
|
||||
orden: servicio?.orden ?? "",
|
||||
activo: servicio?.activo ?? true,
|
||||
soloAdmin: servicio?.soloAdmin ?? false,
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (categoriasProp) return;
|
||||
let vivo = true;
|
||||
fetch("/api/categorias")
|
||||
.then((r) => (r.ok ? r.json() : []))
|
||||
.then((cats: CategoriaOpcion[]) => vivo && setCategorias(cats))
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
vivo = false;
|
||||
};
|
||||
}, [categoriasProp]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === "Escape" && !saving && onClose();
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onClose, saving]);
|
||||
|
||||
const update = (key: keyof typeof form, value: unknown) =>
|
||||
setForm((p) => ({ ...p, [key]: value }));
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.nombre.trim()) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const entregables = form.entregablesDefault
|
||||
.split("\n")
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
const payload: Record<string, unknown> = {
|
||||
nombre: form.nombre.trim(),
|
||||
descripcion: form.descripcion.trim() || null,
|
||||
categoriaId: form.categoriaId || null,
|
||||
tipoPago: form.tipoPago,
|
||||
precioBase: Number(form.precioBase) || 0,
|
||||
tiempoEntrega: form.tiempoEntrega.trim() || "4 - 10 dias",
|
||||
entregablesDefault: entregables,
|
||||
variante: form.variante.trim() || null,
|
||||
nivel: form.nivel || null,
|
||||
fase: Number(form.fase),
|
||||
};
|
||||
if (avanzado) {
|
||||
if (form.orden !== "") payload.orden = Number(form.orden);
|
||||
payload.activo = form.activo;
|
||||
payload.soloAdmin = form.soloAdmin;
|
||||
}
|
||||
const res = await fetch(editando ? `/api/catalogo/${servicio!.id}` : "/api/catalogo", {
|
||||
method: editando ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error || "No se pudo guardar el servicio");
|
||||
return;
|
||||
}
|
||||
onSaved(data as ServicioCatalogoDatos);
|
||||
} catch {
|
||||
setError("No se pudo conectar con el servidor");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => !saving && onClose()}>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="servicio-modal-titulo"
|
||||
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 id="servicio-modal-titulo" className="font-semibold">
|
||||
{editando ? "Editar servicio" : "Nuevo servicio"}
|
||||
</h3>
|
||||
<button onClick={onClose} aria-label="Cerrar">
|
||||
<X className="w-5 h-5 text-muted" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex-1 p-5 space-y-4">
|
||||
{aviso && (
|
||||
<div className="flex gap-2 text-xs text-muted bg-primary-light/30 border border-primary/20 rounded-lg px-3 py-2">
|
||||
<Info className="w-4 h-4 text-primary shrink-0 mt-0.5" />
|
||||
<span>{aviso}</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="sf-nombre" className="block text-sm font-medium mb-1">Nombre *</label>
|
||||
<input id="sf-nombre"
|
||||
type="text"
|
||||
value={form.nombre}
|
||||
onChange={(e) => update("nombre", e.target.value)}
|
||||
className={INPUT}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-descripcion" className="block text-sm font-medium mb-1">Descripcion</label>
|
||||
<textarea id="sf-descripcion"
|
||||
value={form.descripcion}
|
||||
onChange={(e) => update("descripcion", e.target.value)}
|
||||
rows={2}
|
||||
className={`${INPUT} resize-none`}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="sf-categoria" className="block text-sm font-medium mb-1">Categoria</label>
|
||||
<select id="sf-categoria" value={form.categoriaId} onChange={(e) => update("categoriaId", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="">Sin categoria</option>
|
||||
{categorias.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-tipo-pago" className="block text-sm font-medium mb-1">Tipo de pago</label>
|
||||
<select id="sf-tipo-pago" value={form.tipoPago} onChange={(e) => update("tipoPago", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="unico">Pago unico</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label htmlFor="sf-precio" className="block text-sm font-medium mb-1">Precio base</label>
|
||||
<input id="sf-precio"
|
||||
type="number"
|
||||
value={form.precioBase}
|
||||
onChange={(e) => update("precioBase", e.target.value === "" ? "" : Number(e.target.value))}
|
||||
min={0}
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-fase" className="block text-sm font-medium mb-1">Fase</label>
|
||||
<select id="sf-fase" value={form.fase} onChange={(e) => update("fase", Number(e.target.value))} className={`${INPUT} bg-white`}>
|
||||
{Object.entries(FASES).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-tiempo" className="block text-sm font-medium mb-1">Tiempo de entrega</label>
|
||||
<input id="sf-tiempo" type="text" value={form.tiempoEntrega} onChange={(e) => update("tiempoEntrega", e.target.value)} className={INPUT} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-entregables" className="block text-sm font-medium mb-1">Entregables (uno por linea)</label>
|
||||
<textarea id="sf-entregables"
|
||||
value={form.entregablesDefault}
|
||||
onChange={(e) => update("entregablesDefault", e.target.value)}
|
||||
rows={4}
|
||||
placeholder={"Entregable 1\nEntregable 2"}
|
||||
className={`${INPUT} resize-none font-mono text-xs`}
|
||||
/>
|
||||
</div>
|
||||
<div className={`grid grid-cols-1 gap-4 ${avanzado ? "sm:grid-cols-3" : "sm:grid-cols-2"}`}>
|
||||
<div>
|
||||
<label htmlFor="sf-nivel" className="block text-sm font-medium mb-1">Nivel</label>
|
||||
<select id="sf-nivel" value={form.nivel} onChange={(e) => update("nivel", e.target.value)} className={`${INPUT} bg-white`}>
|
||||
<option value="">Sin nivel</option>
|
||||
{NIVELES.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="sf-variante" className="block text-sm font-medium mb-1">Variante</label>
|
||||
<input id="sf-variante"
|
||||
type="text"
|
||||
value={form.variante}
|
||||
onChange={(e) => update("variante", e.target.value)}
|
||||
placeholder="Ej: WooCommerce, Shopify..."
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
{avanzado && (
|
||||
<div>
|
||||
<label htmlFor="sf-orden" className="block text-sm font-medium mb-1">Orden</label>
|
||||
<input id="sf-orden"
|
||||
type="number"
|
||||
value={form.orden}
|
||||
onChange={(e) => update("orden", e.target.value === "" ? "" : Number(e.target.value))}
|
||||
min={0}
|
||||
placeholder="Al final"
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{avanzado && (
|
||||
<div className="space-y-2">
|
||||
<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 (visible al cotizar)
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.soloAdmin}
|
||||
onChange={(e) => update("soloAdmin", e.target.checked)}
|
||||
className="rounded border-border"
|
||||
/>
|
||||
Solo administrador (oculto para bots y agentes IA)
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-danger bg-danger/10 border border-danger/30 rounded-lg px-3 py-2">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-3">
|
||||
<button onClick={onClose} disabled={saving} 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" />}
|
||||
{editando ? "Guardar cambios" : textoCrear}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Link, useLocation, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
FileText,
|
||||
Database,
|
||||
Users,
|
||||
Receipt,
|
||||
Settings,
|
||||
Menu,
|
||||
X,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
|
||||
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: "Cobros", href: "/cobros", icon: Receipt },
|
||||
{ name: "Configuracion", href: "/configuracion", icon: Settings },
|
||||
];
|
||||
|
||||
export default function Sidebar() {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { setUser } = useAuth();
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
} catch {
|
||||
// Aunque falle la peticion, limpiamos la sesion local.
|
||||
}
|
||||
setUser(null);
|
||||
navigate("/login", { replace: true });
|
||||
};
|
||||
|
||||
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}
|
||||
to={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,296 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AlertTriangle, CheckCircle2, Info, XCircle, X } from "lucide-react";
|
||||
|
||||
// Sistema de ventanas emergentes PROPIO de la plataforma (con su estilo visual),
|
||||
// para reemplazar los diálogos nativos del navegador (confirm/alert/prompt), que
|
||||
// se ven fuera de la marca ("<dominio> dice…"). Se monta una sola vez en el layout
|
||||
// y se consume con los hooks useConfirm / usePrompt / useToast.
|
||||
|
||||
type ConfirmOptions = {
|
||||
title?: string;
|
||||
message: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
danger?: boolean;
|
||||
};
|
||||
|
||||
type PromptOptions = {
|
||||
title?: string;
|
||||
message?: string;
|
||||
label?: string;
|
||||
defaultValue?: string;
|
||||
placeholder?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
};
|
||||
|
||||
type ToastKind = "success" | "error" | "info";
|
||||
type ToastItem = { id: number; message: string; kind: ToastKind };
|
||||
|
||||
type DialogContextValue = {
|
||||
confirm: (opts: ConfirmOptions | string) => Promise<boolean>;
|
||||
prompt: (opts: PromptOptions | string) => Promise<string | null>;
|
||||
toast: (message: string, kind?: ToastKind) => void;
|
||||
};
|
||||
|
||||
const DialogContext = createContext<DialogContextValue | null>(null);
|
||||
|
||||
type ActiveConfirm = { kind: "confirm"; opts: ConfirmOptions; resolve: (v: boolean) => void };
|
||||
type ActivePrompt = { kind: "prompt"; opts: PromptOptions; resolve: (v: string | null) => void };
|
||||
type Active = ActiveConfirm | ActivePrompt | null;
|
||||
|
||||
export function DialogProvider({ children }: { children: React.ReactNode }) {
|
||||
const [active, setActive] = useState<Active>(null);
|
||||
const [promptValue, setPromptValue] = useState("");
|
||||
const [toasts, setToasts] = useState<ToastItem[]>([]);
|
||||
const toastSeq = useRef(0);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const confirmBtnRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const confirm = useCallback((o: ConfirmOptions | string) => {
|
||||
const opts = typeof o === "string" ? { message: o } : o;
|
||||
return new Promise<boolean>((resolve) => setActive({ kind: "confirm", opts, resolve }));
|
||||
}, []);
|
||||
|
||||
const prompt = useCallback((o: PromptOptions | string) => {
|
||||
const opts = typeof o === "string" ? { message: o } : o;
|
||||
setPromptValue(opts.defaultValue ?? "");
|
||||
return new Promise<string | null>((resolve) => setActive({ kind: "prompt", opts, resolve }));
|
||||
}, []);
|
||||
|
||||
const toast = useCallback((message: string, kind: ToastKind = "info") => {
|
||||
const id = ++toastSeq.current;
|
||||
setToasts((t) => [...t, { id, message, kind }]);
|
||||
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 4500);
|
||||
}, []);
|
||||
|
||||
// Resuelven la promesa del diálogo activo y lo cierran. Se ejecutan en manejadores
|
||||
// de eventos (post-render), capturando el `active` vigente: nada de efectos dentro
|
||||
// del updater de setState (evita dobles resoluciones en StrictMode).
|
||||
const finishConfirm = (v: boolean) => {
|
||||
if (active?.kind === "confirm") active.resolve(v);
|
||||
setActive(null);
|
||||
};
|
||||
const finishPrompt = (v: string | null) => {
|
||||
if (active?.kind === "prompt") active.resolve(v);
|
||||
setActive(null);
|
||||
};
|
||||
const dismiss = () => {
|
||||
if (active?.kind === "confirm") active.resolve(false);
|
||||
else if (active?.kind === "prompt") active.resolve(null);
|
||||
setActive(null);
|
||||
};
|
||||
|
||||
// Foco automático al abrir + cerrar con Escape.
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const t = setTimeout(() => {
|
||||
if (active.kind === "prompt") inputRef.current?.focus();
|
||||
else confirmBtnRef.current?.focus();
|
||||
}, 30);
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape") return;
|
||||
if (active.kind === "confirm") active.resolve(false);
|
||||
else active.resolve(null);
|
||||
setActive(null);
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [active]);
|
||||
|
||||
const value = useMemo(() => ({ confirm, prompt, toast }), [confirm, prompt, toast]);
|
||||
|
||||
return (
|
||||
<DialogContext.Provider value={value}>
|
||||
{children}
|
||||
|
||||
{active && (
|
||||
<div
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={dismiss}
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-xl bg-card-bg border border-border shadow-2xl overflow-hidden"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
{active.kind === "confirm" ? (
|
||||
<ConfirmBody
|
||||
opts={active.opts}
|
||||
confirmBtnRef={confirmBtnRef}
|
||||
onCancel={() => finishConfirm(false)}
|
||||
onConfirm={() => finishConfirm(true)}
|
||||
/>
|
||||
) : (
|
||||
<PromptBody
|
||||
opts={active.opts}
|
||||
value={promptValue}
|
||||
setValue={setPromptValue}
|
||||
inputRef={inputRef}
|
||||
onCancel={() => finishPrompt(null)}
|
||||
onSubmit={() => finishPrompt(promptValue)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Avisos (toasts) */}
|
||||
<div className="fixed bottom-4 right-4 z-[110] flex flex-col gap-2 max-w-[calc(100vw-2rem)]">
|
||||
{toasts.map((t) => (
|
||||
<ToastCard key={t.id} item={t} onClose={() => setToasts((ts) => ts.filter((x) => x.id !== t.id))} />
|
||||
))}
|
||||
</div>
|
||||
</DialogContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfirmBody({
|
||||
opts,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
confirmBtnRef,
|
||||
}: {
|
||||
opts: ConfirmOptions;
|
||||
onCancel: () => void;
|
||||
onConfirm: () => void;
|
||||
confirmBtnRef: React.RefObject<HTMLButtonElement | null>;
|
||||
}) {
|
||||
return (
|
||||
<div className="p-5">
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={`mt-0.5 shrink-0 rounded-full p-2 ${
|
||||
opts.danger ? "bg-red-100 text-red-600" : "bg-primary-light text-primary"
|
||||
}`}
|
||||
>
|
||||
{opts.danger ? <AlertTriangle className="w-5 h-5" /> : <Info className="w-5 h-5" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
{opts.title && <h3 className="font-semibold text-base mb-1">{opts.title}</h3>}
|
||||
<p className="text-sm text-foreground/80 whitespace-pre-line">{opts.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
{opts.cancelText || "Cancelar"}
|
||||
</button>
|
||||
<button
|
||||
ref={confirmBtnRef}
|
||||
type="button"
|
||||
onClick={onConfirm}
|
||||
className={`px-4 py-2 rounded-lg text-sm text-white hover:opacity-90 ${
|
||||
opts.danger ? "bg-red-600" : "bg-primary"
|
||||
}`}
|
||||
>
|
||||
{opts.confirmText || "Aceptar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PromptBody({
|
||||
opts,
|
||||
value,
|
||||
setValue,
|
||||
inputRef,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
}: {
|
||||
opts: PromptOptions;
|
||||
value: string;
|
||||
setValue: (v: string) => void;
|
||||
inputRef: React.RefObject<HTMLInputElement | null>;
|
||||
onCancel: () => void;
|
||||
onSubmit: () => void;
|
||||
}) {
|
||||
return (
|
||||
<form
|
||||
className="p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
{opts.title && <h3 className="font-semibold text-base mb-1">{opts.title}</h3>}
|
||||
{opts.message && <p className="text-sm text-foreground/80 mb-3">{opts.message}</p>}
|
||||
{opts.label && <label className="block text-xs text-muted mb-1">{opts.label}</label>}
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder={opts.placeholder}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-1 focus:ring-primary"
|
||||
/>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCancel}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
{opts.cancelText || "Cancelar"}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!value.trim()}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{opts.confirmText || "Aceptar"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
const TOAST_STYLE: Record<ToastKind, { cls: string; icon: React.ReactNode }> = {
|
||||
success: { cls: "border-green-200 bg-green-50 text-green-800", icon: <CheckCircle2 className="w-4 h-4" /> },
|
||||
error: { cls: "border-red-200 bg-red-50 text-red-800", icon: <XCircle className="w-4 h-4" /> },
|
||||
info: { cls: "border-blue-200 bg-blue-50 text-blue-800", icon: <Info className="w-4 h-4" /> },
|
||||
};
|
||||
|
||||
function ToastCard({ item, onClose }: { item: ToastItem; onClose: () => void }) {
|
||||
const s = TOAST_STYLE[item.kind];
|
||||
return (
|
||||
<div
|
||||
className={`flex items-start gap-2 rounded-lg border px-3 py-2 shadow-lg text-sm ${s.cls}`}
|
||||
role="status"
|
||||
>
|
||||
<span className="mt-0.5 shrink-0">{s.icon}</span>
|
||||
<span className="min-w-0 break-words">{item.message}</span>
|
||||
<button onClick={onClose} className="ml-1 shrink-0 opacity-60 hover:opacity-100" aria-label="Cerrar aviso">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function useDialogs(): DialogContextValue {
|
||||
const ctx = useContext(DialogContext);
|
||||
if (!ctx) throw new Error("useDialogs debe usarse dentro de <DialogProvider>");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
export const useConfirm = () => useDialogs().confirm;
|
||||
export const usePrompt = () => useDialogs().prompt;
|
||||
export const useToast = () => useDialogs().toast;
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export function LoadingScreen({
|
||||
mensaje,
|
||||
label,
|
||||
}: {
|
||||
mensaje?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const texto = mensaje ?? label ?? "Cargando...";
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20 text-muted">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-primary" />
|
||||
<span>{texto}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageError({
|
||||
mensaje,
|
||||
message,
|
||||
onRetry,
|
||||
}: {
|
||||
mensaje?: string;
|
||||
message?: string;
|
||||
onRetry?: () => void;
|
||||
}) {
|
||||
const texto = mensaje ?? message ?? "No se pudo cargar la información";
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-10 text-center">
|
||||
<p className="text-sm text-muted mb-3">{texto}</p>
|
||||
{onRetry && (
|
||||
<button
|
||||
onClick={onRetry}
|
||||
className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary-dark"
|
||||
>
|
||||
Reintentar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useId, useRef } from "react";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
// Ventana modal con formulario (para lo que no cabe en useConfirm/usePrompt:
|
||||
// varios campos). Misma piel que los dialogos de DialogProvider; cierra con
|
||||
// Escape o clic fuera y enfoca el primer campo al abrir.
|
||||
export function Modal({
|
||||
titulo,
|
||||
descripcion,
|
||||
onClose,
|
||||
onSubmit,
|
||||
children,
|
||||
acciones,
|
||||
ancho = "max-w-md",
|
||||
}: {
|
||||
titulo: string;
|
||||
descripcion?: React.ReactNode;
|
||||
onClose: () => void;
|
||||
onSubmit: () => void;
|
||||
children: React.ReactNode;
|
||||
// Botones del pie (el de enviar debe ser type="submit").
|
||||
acciones: React.ReactNode;
|
||||
ancho?: string;
|
||||
}) {
|
||||
const tituloId = useId();
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
// onClose cambia en cada render del padre; el listener usa siempre el ultimo.
|
||||
const cerrarRef = useRef(onClose);
|
||||
useEffect(() => {
|
||||
cerrarRef.current = onClose;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => {
|
||||
formRef.current
|
||||
?.querySelector<HTMLElement>("input:not([type=hidden]), select, textarea")
|
||||
?.focus();
|
||||
}, 30);
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") cerrarRef.current();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={onClose}
|
||||
role="presentation"
|
||||
>
|
||||
<div
|
||||
className={`w-full ${ancho} max-h-[calc(100dvh-2rem)] overflow-y-auto rounded-xl bg-card-bg border border-border shadow-2xl`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={tituloId}
|
||||
>
|
||||
<form
|
||||
ref={formRef}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4 px-5 pt-5">
|
||||
<div className="min-w-0">
|
||||
<h2 id={tituloId} className="font-semibold text-base">
|
||||
{titulo}
|
||||
</h2>
|
||||
{descripcion && <p className="text-sm text-muted mt-1">{descripcion}</p>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="-mr-1 shrink-0 rounded p-1 text-muted hover:text-foreground hover:bg-gray-100"
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-5 py-4 space-y-3">{children}</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-2">{acciones}</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Estilos compartidos de los campos de formulario dentro de un Modal.
|
||||
export const claseCampo =
|
||||
"w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary";
|
||||
export const claseEtiqueta = "block text-xs font-medium text-muted mb-1";
|
||||
export const claseBotonSecundario =
|
||||
"px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50";
|
||||
export const claseBotonPrimario =
|
||||
"px-4 py-2 rounded-lg text-sm font-medium text-white bg-primary hover:opacity-90 disabled:opacity-50";
|
||||
@@ -0,0 +1,80 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--font-figtree: "Figtree", sans-serif;
|
||||
--font-archivo: "Archivo", sans-serif;
|
||||
--font-geist-mono: "Geist Mono", monospace;
|
||||
--background: #f8fafc;
|
||||
--foreground: #0f172a;
|
||||
--primary: #0400c4;
|
||||
--primary-dark: #03009a;
|
||||
--primary-light: #e8e8ff;
|
||||
--secondary: #0f172a;
|
||||
--accent: #06b6d4;
|
||||
--success: #10b981;
|
||||
--warning: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
--sidebar-bg: #0f172a;
|
||||
--sidebar-text: #cbd5e1;
|
||||
--sidebar-active: #0400c4;
|
||||
--card-bg: #ffffff;
|
||||
--border: #e2e8f0;
|
||||
/* Texto secundario: slate-500 da 4.8:1 sobre blanco (slate-400 se quedaba en
|
||||
2.6:1, ilegible para cifras y fechas). */
|
||||
--muted: #64748b;
|
||||
}
|
||||
|
||||
@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-figtree);
|
||||
--font-heading: var(--font-archivo);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: var(--font-sans), Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
.font-display {
|
||||
font-family: var(--font-heading), var(--font-sans), Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #cbd5e1 transparent;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: var(--primary-light);
|
||||
color: var(--primary-dark);
|
||||
}
|
||||
|
||||
/* Foco de teclado visible y consistente; el mouse no lo dispara. */
|
||||
a:focus-visible,
|
||||
button:focus-visible,
|
||||
summary:focus-visible,
|
||||
label:focus-within:has(input[type="file"]) {
|
||||
outline: 2px solid var(--primary);
|
||||
outline-offset: 2px;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
export interface BrandingConfig {
|
||||
colorPrimario?: string;
|
||||
colorSecundario?: string;
|
||||
logoBase64?: string;
|
||||
logoMime?: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_COLOR_PRIMARIO = "#0400C4";
|
||||
export const DEFAULT_COLOR_SECUNDARIO = "#0F172A";
|
||||
|
||||
export function parseBrandingFromConfig(map: Record<string, string>): BrandingConfig {
|
||||
const rawLogo = map.logo_base64;
|
||||
return {
|
||||
colorPrimario: map.color_primario || DEFAULT_COLOR_PRIMARIO,
|
||||
colorSecundario: map.color_secundario || DEFAULT_COLOR_SECUNDARIO,
|
||||
logoBase64: rawLogo
|
||||
? rawLogo.includes(":")
|
||||
? rawLogo.split(":").slice(1).join(":")
|
||||
: rawLogo
|
||||
: undefined,
|
||||
logoMime: rawLogo
|
||||
? rawLogo.includes(":")
|
||||
? rawLogo.split(":")[0]
|
||||
: "image/png"
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export interface PaqueteServicioItem {
|
||||
id: string;
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precioBase: number;
|
||||
tiempoEntrega: string;
|
||||
entregablesDefault: string[];
|
||||
nivel: string | null;
|
||||
}
|
||||
|
||||
export interface PaqueteNormalizado {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fases: {
|
||||
id: string;
|
||||
nombre: string;
|
||||
orden: number;
|
||||
servicios: PaqueteServicioItem[];
|
||||
}[];
|
||||
}
|
||||
|
||||
// Normaliza la respuesta de GET /api/paquetes tanto si `fases[].servicios` viene
|
||||
// plano (ServicioCatalogo) como si viene envuelto en `{ servicio: ... }` (Prisma join).
|
||||
export function normalizarPaquetes(raw: unknown): PaqueteNormalizado[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.map((p: Record<string, unknown>) => {
|
||||
const fasesRaw = Array.isArray(p.fases) ? (p.fases as Record<string, unknown>[]) : [];
|
||||
return {
|
||||
id: String(p.id ?? ""),
|
||||
nombre: String(p.nombre ?? ""),
|
||||
descripcion: typeof p.descripcion === "string" ? p.descripcion : null,
|
||||
fases: fasesRaw.map((f) => {
|
||||
const servsRaw = Array.isArray(f.servicios) ? (f.servicios as Record<string, unknown>[]) : [];
|
||||
return {
|
||||
id: String(f.id ?? ""),
|
||||
nombre: String(f.nombre ?? ""),
|
||||
orden: Number(f.orden ?? 0),
|
||||
servicios: servsRaw
|
||||
.map((entry) => {
|
||||
const s = (entry.servicio ?? entry) as Record<string, unknown> | undefined;
|
||||
if (!s) return null;
|
||||
return {
|
||||
id: String(s.id ?? ""),
|
||||
nombre: String(s.nombre ?? ""),
|
||||
fase: Number(s.fase ?? 1),
|
||||
tipoPago: String(s.tipoPago ?? "unico"),
|
||||
precioBase: Number(s.precioBase ?? 0),
|
||||
tiempoEntrega: String(s.tiempoEntrega ?? ""),
|
||||
entregablesDefault: Array.isArray(s.entregablesDefault)
|
||||
? (s.entregablesDefault as string[])
|
||||
: [],
|
||||
nivel: typeof s.nivel === "string" ? s.nivel : null,
|
||||
};
|
||||
})
|
||||
.filter((x): x is PaqueteServicioItem => x !== null),
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
export interface SessionUser {
|
||||
userId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
role: string;
|
||||
clienteId?: string | null;
|
||||
clienteNombre?: string | null;
|
||||
}
|
||||
|
||||
interface AuthContextValue {
|
||||
user: SessionUser | null;
|
||||
loading: boolean;
|
||||
setUser: (user: SessionUser | null) => void;
|
||||
refreshUser: () => Promise<SessionUser | null>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<SessionUser | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refreshUser = useCallback(async (): Promise<SessionUser | null> => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me", { credentials: "same-origin" });
|
||||
if (!res.ok) {
|
||||
setUser(null);
|
||||
return null;
|
||||
}
|
||||
const data = (await res.json()) as { user?: SessionUser | null };
|
||||
const u = data?.user ?? null;
|
||||
setUser(u);
|
||||
return u;
|
||||
} catch {
|
||||
setUser(null);
|
||||
return null;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshUser();
|
||||
}, [refreshUser]);
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ user, loading, setUser, refreshUser }),
|
||||
[user, loading, refreshUser]
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error("useAuth debe usarse dentro de <AuthProvider>");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
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).
|
||||
// "demanda" = tarifa por hora sin horas comprometidas; precio=0, no suma al total
|
||||
// (se factura a fin de mes segun consumo). Solo muestra la tarifa y sus beneficios.
|
||||
export const MODELOS_COBRO: Record<string, string> = {
|
||||
fijo: "Precio fijo",
|
||||
horas: "Por horas",
|
||||
retainer: "Retainer (minimo + adicionales)",
|
||||
demanda: "Bajo demanda / por hora",
|
||||
};
|
||||
|
||||
// Sub-linea de desglose por modelo de cobro (horas / retainer / demanda) para PDF/Excel.
|
||||
// Reutilizado por ambos backends para mantener paridad.
|
||||
export function detalleModelo(serv: {
|
||||
modeloCobro?: string | null;
|
||||
esPersonalizado?: boolean | null;
|
||||
horas?: number | null;
|
||||
tarifaHora?: number | null;
|
||||
montoMinimo?: number | null;
|
||||
horasIncluidas?: number | null;
|
||||
}): string {
|
||||
if (serv.modeloCobro === "retainer") {
|
||||
return describirRetainer(serv.montoMinimo ?? 0, serv.horasIncluidas ?? 0, serv.tarifaHora ?? 0);
|
||||
}
|
||||
if (serv.modeloCobro === "demanda") {
|
||||
return `${formatCurrency(serv.tarifaHora ?? 0)}/hr · segun consumo`;
|
||||
}
|
||||
if ((serv.modeloCobro === "horas" || serv.esPersonalizado) && serv.horas && serv.tarifaHora) {
|
||||
return `${serv.horas} h x ${formatCurrency(serv.tarifaHora)}/hr`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// Texto a mostrar en la columna "Precio" de una partida. Para "demanda" muestra la
|
||||
// tarifa por hora en vez de $0 (el precio real depende del consumo). Reutilizado por
|
||||
// UI, PDF y Excel para mantener consistencia.
|
||||
export function precioDisplay(serv: {
|
||||
modeloCobro?: string | null;
|
||||
tarifaHora?: number | null;
|
||||
precio: number;
|
||||
}): string {
|
||||
if (serv.modeloCobro === "demanda") {
|
||||
return `${formatCurrency(serv.tarifaHora || 0)}/hr`;
|
||||
}
|
||||
return formatCurrency(serv.precio);
|
||||
}
|
||||
|
||||
// Nota al pie para las partidas "bajo demanda": no suman al total comprometido y se
|
||||
// facturan segun consumo. Devuelve "" si no hay partidas demanda. Reutilizado por PDF y Excel.
|
||||
export function notaDemanda(
|
||||
servicios: Array<{ modeloCobro?: string | null; nombre?: string | null; tarifaHora?: number | null }>
|
||||
): string {
|
||||
const dem = servicios.filter((s) => s.modeloCobro === "demanda");
|
||||
if (dem.length === 0) return "";
|
||||
const detalle = dem
|
||||
.map((s) => `${s.nombre || "Servicio"} a ${formatCurrency(s.tarifaHora || 0)}/hr`)
|
||||
.join(", ");
|
||||
return `+ Horas facturadas a fin de mes segun consumo (no incluidas en el total): ${detalle}.`;
|
||||
}
|
||||
|
||||
// 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,
|
||||
};
|
||||
}
|
||||
|
||||
// ----- Totales de una cotizacion: FUENTE DE VERDAD UNICA -----
|
||||
// Antes este calculo estaba duplicado a mano con .filter().reduce() en siete
|
||||
// consumidores (PDF, Excel, detalle, PreciosEditables, formulario, lista y dashboard),
|
||||
// con criterios que no coincidian, y el IVA estaba hardcodeado como * 1.16 en los dos
|
||||
// exportadores ignorando IVA_RATE y el flag incluirIva. Toda comparacion de totales
|
||||
// (y cualquier documento que deba coincidir con el PDF) debe pasar por aqui.
|
||||
//
|
||||
// Nota: los subtotales son SIN IVA, que es como los exportadores presentan hoy los
|
||||
// totales de una cotizacion simple ("los precios no incluyen IVA" en la nota al pie).
|
||||
export interface TotalesCotizacion {
|
||||
subtotalUnico: number;
|
||||
subtotalMensual: number;
|
||||
ivaUnico: number;
|
||||
ivaMensual: number;
|
||||
totalUnico: number;
|
||||
totalMensual: number;
|
||||
/** Desembolso real a 12 meses: unico + mensual x 12, con IVA si aplica.
|
||||
* Es la base del ratio precio/valor de la propuesta consultiva. */
|
||||
totalPrimerAnio: number;
|
||||
incluyeIva: boolean;
|
||||
}
|
||||
|
||||
export function calcularTotalesCotizacion(
|
||||
servicios: Array<{ tipoPago: string; precio: number; seleccionado?: boolean }>,
|
||||
opciones?: { incluirIva?: boolean }
|
||||
): TotalesCotizacion {
|
||||
const incluyeIva = opciones?.incluirIva !== false;
|
||||
const activos = servicios.filter((s) => s.seleccionado !== false);
|
||||
|
||||
const suma = (tipo: string) =>
|
||||
r2(activos.filter((s) => s.tipoPago === tipo).reduce((a, s) => a + (s.precio || 0), 0));
|
||||
|
||||
const subtotalUnico = suma("unico");
|
||||
const subtotalMensual = suma("mensual");
|
||||
|
||||
const ivaUnico = incluyeIva ? r2(subtotalUnico * IVA_RATE) : 0;
|
||||
const ivaMensual = incluyeIva ? r2(subtotalMensual * IVA_RATE) : 0;
|
||||
|
||||
const totalUnico = r2(subtotalUnico + ivaUnico);
|
||||
const totalMensual = r2(subtotalMensual + ivaMensual);
|
||||
|
||||
return {
|
||||
subtotalUnico,
|
||||
subtotalMensual,
|
||||
ivaUnico,
|
||||
ivaMensual,
|
||||
totalUnico,
|
||||
totalMensual,
|
||||
totalPrimerAnio: r2(totalUnico + totalMensual * 12),
|
||||
incluyeIva,
|
||||
};
|
||||
}
|
||||
|
||||
function r2(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
/** Aplica IVA a un monto respetando el flag de la cotizacion.
|
||||
* Sustituye a los `* 1.16` hardcodeados que habia en pdf-generator y excel-builder. */
|
||||
export function conIva(monto: number, incluirIva: boolean = true): number {
|
||||
return r2((monto || 0) * (incluirIva ? 1 + IVA_RATE : 1));
|
||||
}
|
||||
|
||||
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", "aprobada", "enviada", "aceptada", "rechazada", "vencida"] as const;
|
||||
export type EstadoCotizacion = (typeof ESTADOS_COTIZACION)[number];
|
||||
|
||||
// ----- Registro de horas (notas de pago) -----
|
||||
// Modelos de cobro que implican trabajo por tiempo: para estas cotizaciones se
|
||||
// habilita el registro de horas trabajadas y la emision de notas de pago.
|
||||
export const MODELOS_COBRO_TIEMPO = ["horas", "retainer", "demanda"] as const;
|
||||
|
||||
// Una cotizacion es "por tiempo" si al menos una de sus partidas se cobra por horas,
|
||||
// retainer o demanda. Solo en ese caso tiene sentido registrar horas trabajadas.
|
||||
export function esCotizacionPorTiempo(
|
||||
servicios: Array<{ modeloCobro?: string | null }>
|
||||
): boolean {
|
||||
return servicios.some((s) =>
|
||||
(MODELOS_COBRO_TIEMPO as readonly string[]).includes(s.modeloCobro ?? "")
|
||||
);
|
||||
}
|
||||
|
||||
// Tarifa por hora a sugerir al registrar horas: la de la primera partida por tiempo
|
||||
// con tarifa > 0; si no hay, TARIFA_HORA_DEFAULT.
|
||||
export function tarifaHoraSugerida(
|
||||
servicios: Array<{ modeloCobro?: string | null; tarifaHora?: number | null }>
|
||||
): number {
|
||||
const serv = servicios.find(
|
||||
(s) =>
|
||||
(MODELOS_COBRO_TIEMPO as readonly string[]).includes(s.modeloCobro ?? "") &&
|
||||
(s.tarifaHora ?? 0) > 0
|
||||
);
|
||||
return serv?.tarifaHora ?? TARIFA_HORA_DEFAULT;
|
||||
}
|
||||
|
||||
// "09:00" + "13:30" => 4.5. Devuelve 0 si el formato es invalido o fin <= inicio.
|
||||
// No cruza medianoche (un registro = un tramo dentro de un dia).
|
||||
export function calcularHorasRango(horaInicio: string, horaFin: string): number {
|
||||
const re = /^(\d{1,2}):(\d{2})$/;
|
||||
const a = re.exec(horaInicio ?? "");
|
||||
const b = re.exec(horaFin ?? "");
|
||||
if (!a || !b) return 0;
|
||||
const ini = parseInt(a[1], 10) * 60 + parseInt(a[2], 10);
|
||||
const fin = parseInt(b[1], 10) * 60 + parseInt(b[2], 10);
|
||||
if (fin <= ini) return 0;
|
||||
return Math.round(((fin - ini) / 60) * 100) / 100;
|
||||
}
|
||||
|
||||
export type ModoAgrupacion = "detalle" | "dia" | "semana" | "mes";
|
||||
|
||||
export const MODOS_AGRUPACION: { value: ModoAgrupacion; label: string }[] = [
|
||||
{ value: "detalle", label: "Detalle" },
|
||||
{ value: "dia", label: "Por dia" },
|
||||
{ value: "semana", label: "Por semana" },
|
||||
{ value: "mes", label: "Por mes" },
|
||||
];
|
||||
|
||||
const MESES_LARGO = [
|
||||
"enero", "febrero", "marzo", "abril", "mayo", "junio",
|
||||
"julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre",
|
||||
];
|
||||
|
||||
// La fecha de un registro es una fecha-calendario sin huso horario. Para que el dia
|
||||
// no se corra entre servidor (UTC) y cliente (MX), se persiste a las 12:00 UTC y se
|
||||
// lee SIEMPRE con getters UTC. Helper para construir esa fecha desde "YYYY-MM-DD".
|
||||
export function fechaRegistroDesdeISO(fechaISO: string): Date {
|
||||
return new Date(`${fechaISO}T12:00:00.000Z`);
|
||||
}
|
||||
|
||||
// Formato corto de fecha de registro (DD/MM/YYYY) leyendo en UTC.
|
||||
export function formatFechaRegistro(date: Date): string {
|
||||
return new Intl.DateTimeFormat("es-MX", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function lunesDeSemanaUTC(d: Date): Date {
|
||||
const r = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
||||
const dia = r.getUTCDay(); // 0 = domingo
|
||||
const offset = dia === 0 ? -6 : 1 - dia;
|
||||
r.setUTCDate(r.getUTCDate() + offset);
|
||||
return r;
|
||||
}
|
||||
|
||||
// Clave + etiqueta del periodo al que pertenece una fecha, segun el modo de agrupacion.
|
||||
// La clave agrupa; la etiqueta se muestra. Todo en UTC para coherencia de calendario.
|
||||
export function periodoAgrupacion(
|
||||
fecha: Date,
|
||||
modo: ModoAgrupacion
|
||||
): { clave: string; etiqueta: string } {
|
||||
const y = fecha.getUTCFullYear();
|
||||
const m = fecha.getUTCMonth();
|
||||
const d = fecha.getUTCDate();
|
||||
const p2 = (n: number) => String(n).padStart(2, "0");
|
||||
|
||||
if (modo === "mes") {
|
||||
return { clave: `${y}-${p2(m + 1)}`, etiqueta: `${MESES_LARGO[m]} ${y}` };
|
||||
}
|
||||
if (modo === "semana") {
|
||||
const lunes = lunesDeSemanaUTC(fecha);
|
||||
const domingo = new Date(lunes);
|
||||
domingo.setUTCDate(lunes.getUTCDate() + 6);
|
||||
const fmt = (x: Date) => `${p2(x.getUTCDate())}/${p2(x.getUTCMonth() + 1)}`;
|
||||
const clave = `${lunes.getUTCFullYear()}-${p2(lunes.getUTCMonth() + 1)}-${p2(lunes.getUTCDate())}`;
|
||||
return { clave, etiqueta: `Semana ${fmt(lunes)} - ${fmt(domingo)}` };
|
||||
}
|
||||
// "dia" / "detalle"
|
||||
return { clave: `${y}-${p2(m + 1)}-${p2(d)}`, etiqueta: formatFechaRegistro(fecha) };
|
||||
}
|
||||
|
||||
// Estado de cobro de una partida de horas registrada. "por_pagar" es pendiente de
|
||||
// cobro (entra en la nota por pagar al cliente); "pagada" ya se cobro (se conserva
|
||||
// como recibo/historial y NO se suma al pendiente).
|
||||
export const ESTADOS_PAGO_HORAS = ["por_pagar", "pagada"] as const;
|
||||
export type EstadoPagoHoras = (typeof ESTADOS_PAGO_HORAS)[number];
|
||||
|
||||
export const ESTADOS_PAGO_HORAS_LABEL: Record<EstadoPagoHoras, string> = {
|
||||
por_pagar: "Por pagar",
|
||||
pagada: "Pagada",
|
||||
};
|
||||
|
||||
// Normaliza el estado de pago: cualquier valor distinto de "pagada" cuenta como pendiente.
|
||||
export function esPagada(estadoPago?: string | null): boolean {
|
||||
return estadoPago === "pagada";
|
||||
}
|
||||
|
||||
// Suma horas e importe de un conjunto de registros separando por estado de pago, para
|
||||
// que lo pagado y lo pendiente nunca se mezclen en un solo total.
|
||||
export function resumenPagoHoras(
|
||||
registros: Array<{ horas: number; tarifaHora: number; estadoPago?: string | null }>
|
||||
): {
|
||||
porPagar: { horas: number; importe: number; count: number };
|
||||
pagada: { horas: number; importe: number; count: number };
|
||||
total: { horas: number; importe: number; count: number };
|
||||
} {
|
||||
const acc = () => ({ horas: 0, importe: 0, count: 0 });
|
||||
const r = { porPagar: acc(), pagada: acc(), total: acc() };
|
||||
for (const x of registros) {
|
||||
const importe = (x.horas || 0) * (x.tarifaHora || 0);
|
||||
const bucket = esPagada(x.estadoPago) ? r.pagada : r.porPagar;
|
||||
bucket.horas += x.horas || 0;
|
||||
bucket.importe += importe;
|
||||
bucket.count += 1;
|
||||
r.total.horas += x.horas || 0;
|
||||
r.total.importe += importe;
|
||||
r.total.count += 1;
|
||||
}
|
||||
for (const k of ["porPagar", "pagada", "total"] as const) {
|
||||
r[k].horas = Math.round(r[k].horas * 100) / 100;
|
||||
r[k].importe = Math.round(r[k].importe * 100) / 100;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
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,246 @@
|
||||
// Utilidades PURAS de los cobros recurrentes: fechas de calendario, estados y
|
||||
// formatos.
|
||||
//
|
||||
// CONVENCION DE FECHAS: una fecha de cobro es una FECHA DE CALENDARIO en
|
||||
// America/Mexico_City, persistida como medianoche UTC de ese calendario
|
||||
// (Date.UTC(y, m-1, d)). Se escribe con parseFechaCalendario() y se muestra
|
||||
// con formatFechaCobro(). Asi "sabado" es sabado en Mexico aunque el servidor
|
||||
// este en UTC.
|
||||
|
||||
export interface ProgramaPagoCalendario {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
fechaInicio: Date | string;
|
||||
fechaFin?: Date | string | null;
|
||||
}
|
||||
|
||||
export const ZONA_HORARIA = "America/Mexico_City";
|
||||
|
||||
export const ESTADOS_PAGO = {
|
||||
PENDIENTE: "pendiente", // generado, sin comprobante
|
||||
EN_REVISION: "en_revision", // comprobante subido, esperando al admin
|
||||
VERIFICADO: "verificado", // admin acepto el comprobante o registro el pago a mano
|
||||
RECHAZADO: "rechazado", // admin rechazo (el archivo se borro; se puede volver a subir)
|
||||
ANULADO: "anulado", // admin lo dejo sin cargo (semana sin servicio, cortesia)
|
||||
} as const;
|
||||
|
||||
export type EstadoPago = (typeof ESTADOS_PAGO)[keyof typeof ESTADOS_PAGO];
|
||||
|
||||
// Estados en los que el cliente todavia DEBE el cobro: nunca subio comprobante
|
||||
// o se lo rechazaron. en_revision no cuenta (ya pago, falta que el admin lo
|
||||
// valide). Es la base del saldo pendiente y de los recordatorios.
|
||||
export const ESTADOS_POR_PAGAR: EstadoPago[] = [ESTADOS_PAGO.PENDIENTE, ESTADOS_PAGO.RECHAZADO];
|
||||
|
||||
export function esPorPagar(estado: string): boolean {
|
||||
return (ESTADOS_POR_PAGAR as string[]).includes(estado);
|
||||
}
|
||||
|
||||
// RECORDATORIOS. Cada cuantos dias el scheduler vuelve a avisar al cliente de
|
||||
// lo que sigue por pagar (0 = sin recordatorio automatico; el envio manual
|
||||
// desde /cobros funciona igual). Se lee en servidor de COBROS_RECORDATORIO_DIAS.
|
||||
export const RECORDATORIO_DIAS_DEFAULT = 3;
|
||||
// Hora local de Mexico a partir de la cual el scheduler puede enviarlos, para
|
||||
// no mandar correos de cobranza a la 1 a. m. cuando cambia el dia.
|
||||
export const HORA_RECORDATORIOS = 9;
|
||||
|
||||
// "YYYY-MM-DD" (input de formularios) -> Date en medianoche UTC del calendario.
|
||||
export function parseFechaCalendario(iso: string): Date {
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso.trim());
|
||||
if (!m) throw new Error(`Fecha invalida: ${iso} (se espera YYYY-MM-DD)`);
|
||||
return new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
||||
}
|
||||
|
||||
// Date -> { y, m, d } usando las partes UTC (la fecha ya es calendario).
|
||||
export function aCalendario(date: Date): { y: number; m: number; d: number } {
|
||||
return { y: date.getUTCFullYear(), m: date.getUTCMonth() + 1, d: date.getUTCDate() };
|
||||
}
|
||||
|
||||
// Fecha de calendario en America/Mexico_City (UTC midnight) del instante dado.
|
||||
// Para timestamps reales (createdAt, ultimoRecordatorioAt), no para fechas de
|
||||
// cobro, que ya son calendario.
|
||||
export function calendarioDe(instante: Date): Date {
|
||||
const iso = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone: ZONA_HORARIA,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
}).format(instante); // "YYYY-MM-DD"
|
||||
return parseFechaCalendario(iso);
|
||||
}
|
||||
|
||||
// Hoy en America/Mexico_City como fecha de calendario (UTC midnight).
|
||||
export function hoyCalendario(): Date {
|
||||
return calendarioDe(new Date());
|
||||
}
|
||||
|
||||
// Hora (0-23) actual en America/Mexico_City.
|
||||
export function horaMexico(instante: Date = new Date()): number {
|
||||
const h = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: ZONA_HORARIA,
|
||||
hour: "numeric",
|
||||
hourCycle: "h23",
|
||||
}).format(instante);
|
||||
return Number(h);
|
||||
}
|
||||
|
||||
// Instante que representa un dia de pago (fecha de calendario MX): mediodia en
|
||||
// Mexico (18:00 UTC; sin horario de verano desde 2022). Para verificadoAt de
|
||||
// los pagos registrados a mano: a medianoche UTC se veria como el dia anterior
|
||||
// al pasarlo por calendarioDe().
|
||||
export function instanteDePago(fecha: Date): Date {
|
||||
const { y, m, d } = aCalendario(fecha);
|
||||
return new Date(Date.UTC(y, m - 1, d, 18));
|
||||
}
|
||||
|
||||
export function sumarDias(d: Date, dias: number): Date {
|
||||
return new Date(d.getTime() + dias * 86400000);
|
||||
}
|
||||
|
||||
// Dias completos entre una fecha de cobro y hoy MX (0 si vence hoy o despues).
|
||||
export function diasDeAtraso(fecha: Date, hoy: Date = hoyCalendario()): number {
|
||||
return Math.max(0, Math.round((hoy.getTime() - fecha.getTime()) / 86400000));
|
||||
}
|
||||
|
||||
const fmtFecha = new Intl.DateTimeFormat("es-MX", {
|
||||
weekday: "long",
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
timeZone: "UTC", // la fecha YA es calendario en UTC; no convertir zona
|
||||
});
|
||||
|
||||
// "Sabado, 04 de julio de 2026" para mostrar en el panel/PDF/correo.
|
||||
export function formatFechaCobro(date: Date): string {
|
||||
const s = fmtFecha.format(date);
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
// Monto en su moneda: "$4,500" / "$4,500.50" / "USD 25". Sin decimales si es
|
||||
// entero, como formatCurrency; a diferencia de este, respeta USD.
|
||||
export function formatMonto(monto: number, moneda: string = "MXN"): string {
|
||||
return new Intl.NumberFormat("es-MX", {
|
||||
style: "currency",
|
||||
currency: moneda || "MXN",
|
||||
minimumFractionDigits: Number.isInteger(monto) ? 0 : 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(monto);
|
||||
}
|
||||
|
||||
// Suma por moneda: un cliente puede tener programas en MXN y USD y no se
|
||||
// deben mezclar en un solo total.
|
||||
export function totalesPorMoneda(
|
||||
pagos: Array<{ monto: number; programa: { moneda: string } }>
|
||||
): Record<string, number> {
|
||||
const totales: Record<string, number> = {};
|
||||
for (const p of pagos) {
|
||||
const moneda = p.programa.moneda || "MXN";
|
||||
totales[moneda] = (totales[moneda] ?? 0) + p.monto;
|
||||
}
|
||||
return totales;
|
||||
}
|
||||
|
||||
// Totales por moneda en una linea: "$2,250" o "$1,500 + USD 100".
|
||||
export function formatTotales(totales: Record<string, number>): string {
|
||||
const partes = Object.entries(totales).map(([moneda, total]) => formatMonto(total, moneda));
|
||||
return partes.length ? partes.join(" + ") : "$0";
|
||||
}
|
||||
|
||||
const fmtDiaSemana = new Intl.DateTimeFormat("es-MX", { weekday: "short", timeZone: "UTC" });
|
||||
const fmtMesCorto = new Intl.DateTimeFormat("es-MX", { month: "short", timeZone: "UTC" });
|
||||
|
||||
// "sáb 31 oct" (agrega el año si no es el de `hoy`). Para listas de cobros.
|
||||
export function formatFechaBreve(date: Date, hoy: Date = hoyCalendario()): string {
|
||||
const dia = fmtDiaSemana.format(date).replace(".", "");
|
||||
const mes = fmtMesCorto.format(date).replace(".", "");
|
||||
const anio = date.getUTCFullYear() !== hoy.getUTCFullYear() ? ` ${date.getUTCFullYear()}` : "";
|
||||
return `${dia} ${date.getUTCDate()} ${mes}${anio}`;
|
||||
}
|
||||
|
||||
// Dias de `hoy` a `fecha` (negativo si ya paso). Ambas son fechas de calendario.
|
||||
export function diasHasta(fecha: Date, hoy: Date = hoyCalendario()): number {
|
||||
return Math.round((fecha.getTime() - hoy.getTime()) / 86400000);
|
||||
}
|
||||
|
||||
// "vence hoy" / "mañana" / "en 5 días" / "hace 1 día" / "hace 12 días".
|
||||
export function describirVencimiento(fecha: Date, hoy: Date = hoyCalendario()): string {
|
||||
const d = diasHasta(fecha, hoy);
|
||||
if (d === 0) return "vence hoy";
|
||||
if (d === 1) return "mañana";
|
||||
if (d > 1) return `en ${d} días`;
|
||||
return d === -1 ? "hace 1 día" : `hace ${-d} días`;
|
||||
}
|
||||
|
||||
// Version corta: "04/07/2026".
|
||||
export function formatFechaCorta(date: Date): string {
|
||||
const { y, m, d } = aCalendario(date);
|
||||
return `${String(d).padStart(2, "0")}/${String(m).padStart(2, "0")}/${y}`;
|
||||
}
|
||||
|
||||
function toDate(value: Date | string): Date {
|
||||
return value instanceof Date ? value : new Date(value);
|
||||
}
|
||||
|
||||
// Todas las fechas de periodo de un programa desde fechaInicio hasta `hasta`
|
||||
// (inclusive), respetando fechaFin si existe. Cadena:
|
||||
// semanal -> diaSemana (0=dom..6=sab; si no viene, el mismo dia que fechaInicio)
|
||||
// quincenal -> dias 1 y 15 de cada mes
|
||||
// mensual -> diaMes (se recorta al ultimo dia del mes si no existe)
|
||||
export function fechasPeriodo(
|
||||
programa: ProgramaPagoCalendario,
|
||||
hasta: Date
|
||||
): Date[] {
|
||||
const inicio = aCalendario(toDate(programa.fechaInicio));
|
||||
const inicioD = new Date(Date.UTC(inicio.y, inicio.m - 1, inicio.d));
|
||||
const fin = programa.fechaFin ? aCalendario(toDate(programa.fechaFin)) : null;
|
||||
const finD = fin ? new Date(Date.UTC(fin.y, fin.m - 1, fin.d)) : null;
|
||||
const limite = finD && finD < hasta ? finD : hasta;
|
||||
if (inicioD > limite) return [];
|
||||
|
||||
const out: Date[] = [];
|
||||
|
||||
if (programa.frecuencia === "semanal") {
|
||||
const dia = programa.diaSemana ?? inicioD.getUTCDay();
|
||||
let d = new Date(inicioD);
|
||||
let guard = 0;
|
||||
while (d.getUTCDay() !== dia && guard++ < 7) d = sumarDias(d, 1);
|
||||
while (d <= limite) {
|
||||
out.push(d);
|
||||
d = sumarDias(d, 7);
|
||||
}
|
||||
} else if (programa.frecuencia === "quincenal") {
|
||||
let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1));
|
||||
while (mes <= limite) {
|
||||
for (const dia of [1, 15]) {
|
||||
const d = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), dia));
|
||||
if (d >= inicioD && d <= limite) out.push(d);
|
||||
}
|
||||
mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1));
|
||||
}
|
||||
} else {
|
||||
// mensual
|
||||
const diaMes = programa.diaMes ?? 1;
|
||||
let mes = new Date(Date.UTC(inicioD.getUTCFullYear(), inicioD.getUTCMonth(), 1));
|
||||
while (mes <= limite) {
|
||||
const ultimoDia = new Date(
|
||||
Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 0)
|
||||
).getUTCDate();
|
||||
const d = new Date(
|
||||
Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth(), Math.min(diaMes, ultimoDia))
|
||||
);
|
||||
if (d >= inicioD && d <= limite) out.push(d);
|
||||
mes = new Date(Date.UTC(mes.getUTCFullYear(), mes.getUTCMonth() + 1, 1));
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// Proxima fecha de cobro >= `desde` (por defecto hoy MX) para el panel admin.
|
||||
export function proximaFecha(
|
||||
programa: ProgramaPagoCalendario,
|
||||
desde: Date = hoyCalendario()
|
||||
): Date | null {
|
||||
const ventana = fechasPeriodo(programa, sumarDias(desde, 366));
|
||||
return ventana.find((f) => f >= desde) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { create } from "zustand";
|
||||
import type { MetaOpcion } from "./calculators";
|
||||
|
||||
export interface ServicioSeleccionado {
|
||||
catalogoId: string;
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
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 {
|
||||
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;
|
||||
observacionesInternas: string;
|
||||
// Doble propuesta: dos opciones comparables dentro de una misma cotizacion.
|
||||
esDoble: boolean;
|
||||
opciones: { "1"?: MetaOpcion; "2"?: MetaOpcion };
|
||||
}
|
||||
|
||||
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;
|
||||
updateOpcionMeta: (opcion: "1" | "2", parcial: Partial<MetaOpcion>) => 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: "",
|
||||
observacionesInternas: "",
|
||||
esDoble: false,
|
||||
opciones: {},
|
||||
};
|
||||
|
||||
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 } })),
|
||||
|
||||
updateOpcionMeta: (opcion, parcial) =>
|
||||
set((state) => ({
|
||||
draft: {
|
||||
...state.draft,
|
||||
opciones: {
|
||||
...state.draft.opciones,
|
||||
[opcion]: { ...state.draft.opciones[opcion], ...parcial },
|
||||
},
|
||||
},
|
||||
})),
|
||||
|
||||
resetDraft: () => set({ draft: { ...initialDraft } }),
|
||||
}));
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,267 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { CheckCircle2, AlertTriangle, Loader2, ShieldCheck } from "lucide-react";
|
||||
import { formatCurrency, formatDate } from "@/lib/calculators";
|
||||
|
||||
interface PartidaResumen {
|
||||
id: string;
|
||||
nombre: string;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
}
|
||||
|
||||
interface AprobarCotizacionData {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
moneda: string;
|
||||
estado: string;
|
||||
vigencia?: string;
|
||||
vigenciaTexto?: string;
|
||||
creadaPorAgente: string | null;
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
totales?: { totalUnico: number; totalMensual: number };
|
||||
totalUnico?: number;
|
||||
totalMensual?: number;
|
||||
incluirIva: boolean;
|
||||
partidas: PartidaResumen[];
|
||||
}
|
||||
|
||||
interface AprobarApiResponse {
|
||||
cotizacion: AprobarCotizacionData;
|
||||
puedeAprobar: boolean;
|
||||
expiraAt?: string;
|
||||
}
|
||||
|
||||
export default function AprobarTokenPage() {
|
||||
const { token = "" } = useParams<{ token: string }>();
|
||||
const [cargando, setCargando] = useState(true);
|
||||
const [motivoInvalido, setMotivoInvalido] = useState<string | null>(null);
|
||||
const [data, setData] = useState<AprobarApiResponse | null>(null);
|
||||
const [estado, setEstado] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [aprobadaOk, setAprobadaOk] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let vivo = true;
|
||||
setCargando(true);
|
||||
setMotivoInvalido(null);
|
||||
fetch(`/api/aprobar/${encodeURIComponent(token)}`)
|
||||
.then(async (res) => {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!vivo) return;
|
||||
if (!res.ok) {
|
||||
setMotivoInvalido(
|
||||
body.error || "Este enlace de aprobación no está disponible."
|
||||
);
|
||||
return;
|
||||
}
|
||||
const payload = body as AprobarApiResponse;
|
||||
setData(payload);
|
||||
setEstado(payload.cotizacion.estado);
|
||||
})
|
||||
.catch(() => {
|
||||
if (vivo) setMotivoInvalido("Error de conexión al verificar el enlace.");
|
||||
})
|
||||
.finally(() => {
|
||||
if (vivo) setCargando(false);
|
||||
});
|
||||
return () => {
|
||||
vivo = false;
|
||||
};
|
||||
}, [token]);
|
||||
|
||||
if (cargando) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4">
|
||||
<div className="flex items-center gap-2 text-sm text-[#64748b]">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-[#0400C4]" />
|
||||
Verificando enlace de aprobación…
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (motivoInvalido || !data) {
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] flex items-center justify-center p-4">
|
||||
<div className="max-w-md w-full bg-white rounded-2xl border border-[#e2e8f0] shadow-sm p-6 text-center">
|
||||
<p className="text-xs tracking-[0.12em] uppercase text-[#0400C4] font-semibold">
|
||||
Uriel Jareth Consulting
|
||||
</p>
|
||||
<h1 className="text-lg font-bold text-[#0F172A] mt-2">Enlace no disponible</h1>
|
||||
<p className="text-sm text-[#64748b] mt-2">
|
||||
{motivoInvalido || "Este enlace de aprobación no es válido."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { cotizacion, puedeAprobar } = data;
|
||||
const totalUnico = cotizacion.totales?.totalUnico ?? cotizacion.totalUnico ?? 0;
|
||||
const totalMensual = cotizacion.totales?.totalMensual ?? cotizacion.totalMensual ?? 0;
|
||||
const vigenciaTexto =
|
||||
cotizacion.vigenciaTexto ||
|
||||
(cotizacion.vigencia ? formatDate(new Date(cotizacion.vigencia)) : "—");
|
||||
|
||||
const handleAprobar = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/aprobar/${encodeURIComponent(token)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ confirmar: true }),
|
||||
});
|
||||
const resBody = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(resBody.error || "No se pudo aprobar la cotización");
|
||||
return;
|
||||
}
|
||||
setEstado("aprobada");
|
||||
setAprobadaOk(true);
|
||||
} catch {
|
||||
setError("Error de red al confirmar la aprobación");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[#f8fafc] py-10 px-4">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<div className="bg-white rounded-2xl border border-[#e2e8f0] shadow-sm overflow-hidden">
|
||||
<div className="bg-[#0F172A] text-white px-6 py-5 flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs tracking-[0.12em] uppercase text-blue-300 font-semibold">
|
||||
Uriel Jareth Consulting
|
||||
</p>
|
||||
<h1 className="text-xl font-bold mt-1">Revisión y aprobación de cotización</h1>
|
||||
</div>
|
||||
<ShieldCheck className="w-8 h-8 text-blue-300 shrink-0" />
|
||||
</div>
|
||||
|
||||
<div className="p-6 space-y-6">
|
||||
{aprobadaOk && (
|
||||
<div className="rounded-xl bg-green-50 border border-green-200 p-4 flex items-start gap-3">
|
||||
<CheckCircle2 className="w-5 h-5 text-green-600 shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-semibold text-green-900">Cotización aprobada correctamente</p>
|
||||
<p className="text-sm text-green-800 mt-0.5">
|
||||
La cotización <strong>{cotizacion.numero}</strong> quedó autorizada y lista para enviarse al cliente.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-xl bg-red-50 border border-red-200 p-4 flex items-start gap-3">
|
||||
<AlertTriangle className="w-5 h-5 text-red-600 shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-red-800">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 text-sm bg-[#f8fafc] rounded-xl border border-[#e2e8f0] p-4">
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Folio</span>
|
||||
<span className="font-semibold text-[#0F172A]">{cotizacion.numero}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Estado actual</span>
|
||||
<span className="font-semibold text-[#0F172A] capitalize">{estado}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Cliente</span>
|
||||
<span className="font-medium text-[#0F172A]">
|
||||
{cotizacion.cliente.nombre}
|
||||
{cotizacion.cliente.empresa ? ` · ${cotizacion.cliente.empresa}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Proyecto</span>
|
||||
<span className="font-medium text-[#0F172A]">{cotizacion.proyecto}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Vigencia</span>
|
||||
<span className="font-medium text-[#0F172A]">{vigenciaTexto}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-[#64748b] block text-xs">Origen</span>
|
||||
<span className="font-medium text-[#0F172A]">
|
||||
{cotizacion.creadaPorAgente ? `Agente: ${cotizacion.creadaPorAgente}` : "Equipo interno"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold text-[#0F172A] mb-2">Partidas incluidas</h2>
|
||||
<div className="border border-[#e2e8f0] rounded-xl overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-[#f8fafc] text-[#64748b] text-xs">
|
||||
<tr>
|
||||
<th className="text-left py-2.5 px-3 font-medium">Concepto</th>
|
||||
<th className="text-left py-2.5 px-3 font-medium">Tipo</th>
|
||||
<th className="text-right py-2.5 px-3 font-medium">Subtotal</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{cotizacion.partidas.map((p) => (
|
||||
<tr key={p.id} className="border-t border-[#e2e8f0]">
|
||||
<td className="py-2.5 px-3 text-[#0F172A]">{p.nombre}</td>
|
||||
<td className="py-2.5 px-3 text-[#64748b] capitalize">{p.tipoPago}</td>
|
||||
<td className="py-2.5 px-3 text-right font-medium text-[#0F172A]">
|
||||
{formatCurrency(p.precio)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 pt-2 border-t border-[#e2e8f0]">
|
||||
<div className="text-sm text-[#0F172A] space-y-0.5">
|
||||
{totalUnico > 0 && (
|
||||
<div>
|
||||
<span className="text-[#64748b]">Total único ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): </span>
|
||||
<strong>{formatCurrency(totalUnico)} {cotizacion.moneda}</strong>
|
||||
</div>
|
||||
)}
|
||||
{totalMensual > 0 && (
|
||||
<div>
|
||||
<span className="text-[#64748b]">Total mensual ({cotizacion.incluirIva ? "c/IVA" : "s/IVA"}): </span>
|
||||
<strong>{formatCurrency(totalMensual)} {cotizacion.moneda}/mes</strong>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{puedeAprobar && !aprobadaOk && (
|
||||
<button
|
||||
onClick={handleAprobar}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-lg bg-[#0400C4] hover:bg-[#03009e] text-white font-semibold text-sm transition-colors disabled:opacity-50"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Aprobando…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
Aprobar cotización
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
|
||||
export default function LoginPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const esCliente = searchParams.get("panel") === "cliente";
|
||||
const navigate = useNavigate();
|
||||
const { setUser, refreshUser } = useAuth();
|
||||
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) {
|
||||
const data = await res.json();
|
||||
const me = await refreshUser();
|
||||
const role = me?.role ?? data?.user?.role;
|
||||
if (!me && data?.user) {
|
||||
setUser({
|
||||
userId: data.user.userId ?? data.user.id ?? "",
|
||||
email: data.user.email ?? email,
|
||||
name: data.user.name ?? "",
|
||||
role: data.user.role ?? "asesor",
|
||||
clienteId: data.user.clienteId ?? null,
|
||||
});
|
||||
}
|
||||
const destino = role === "cliente" ? "/cliente" : "/";
|
||||
navigate(destino, { replace: true });
|
||||
} else {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError(data.error || "No se pudo iniciar sesión");
|
||||
}
|
||||
} catch {
|
||||
setError("Sin conexión con el servidor. Intenta de nuevo.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background px-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="bg-white rounded-xl shadow-[0_8px_30px_-12px_rgba(15,23,42,0.18)] p-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight text-center mb-1">
|
||||
{esCliente ? "Portal de clientes" : "Cotizador"}
|
||||
</h1>
|
||||
<p className="text-center text-muted text-sm mb-6">
|
||||
{esCliente
|
||||
? "Consulta tus cotizaciones y registra tus pagos"
|
||||
: "Uriel Jareth Consulting"}
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<div role="alert" 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 htmlFor="login-email" className="block text-sm font-medium mb-1">
|
||||
Correo
|
||||
</label>
|
||||
<input
|
||||
id="login-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
placeholder="[email protected]"
|
||||
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 htmlFor="login-password" className="block text-sm font-medium mb-1">
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
placeholder="Tu contraseña"
|
||||
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}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,638 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import {
|
||||
Plus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
X,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
Package,
|
||||
LayoutGrid,
|
||||
Settings,
|
||||
FileDown,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { formatCurrency } from "@/lib/calculators";
|
||||
import { normalizarPaquetes } from "@/lib/api";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { ServicioFormModal } from "@/components/ServicioFormModal";
|
||||
import clsx from "clsx";
|
||||
|
||||
export interface CatalogoServicio {
|
||||
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;
|
||||
nivel: string | null;
|
||||
activo: boolean;
|
||||
soloAdmin?: boolean;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
export interface CatalogoCategoria {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
color: string;
|
||||
activo: boolean;
|
||||
orden: number;
|
||||
}
|
||||
|
||||
export interface FasePaqueteUI {
|
||||
id: string;
|
||||
nombre: string;
|
||||
orden: number;
|
||||
servicios: { id: string; nombre: string; precioBase: number; tipoPago: string; nivel: string | null }[];
|
||||
}
|
||||
|
||||
export interface PaqueteUI {
|
||||
id: string;
|
||||
nombre: string;
|
||||
descripcion: string | null;
|
||||
fases: FasePaqueteUI[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
initialServicios: CatalogoServicio[];
|
||||
initialCategorias: CatalogoCategoria[];
|
||||
initialPaquetes: PaqueteUI[];
|
||||
}
|
||||
|
||||
type Tab = "categorias" | "paquetes" | "servicios";
|
||||
|
||||
export function CatalogoClient({ initialServicios, initialCategorias, initialPaquetes }: Props) {
|
||||
const showConfirm = useConfirm();
|
||||
const showPrompt = usePrompt();
|
||||
const showToast = useToast();
|
||||
const [tab, setTab] = useState<Tab>("servicios");
|
||||
const [servicios, setServicios] = useState<CatalogoServicio[]>(initialServicios);
|
||||
const [categorias, setCategorias] = useState<CatalogoCategoria[]>(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(normalizarPaquetes(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).`;
|
||||
showToast(msg, "success");
|
||||
if (data.errores?.length) showToast(`Errores:\n${data.errores.join("\n")}`, "error");
|
||||
await refresh();
|
||||
} else {
|
||||
showToast(data.error || "Error al importar", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al importar CSV", "error");
|
||||
} 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(); showToast(e.error, "error"); }
|
||||
};
|
||||
|
||||
const toggleCategoriaActivo = async (cat: CatalogoCategoria) => {
|
||||
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) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Eliminar paquete",
|
||||
message: "¿Eliminar este paquete y todas sus fases?",
|
||||
confirmText: "Eliminar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) 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 = await showPrompt({
|
||||
title: "Nuevo paquete",
|
||||
label: "Nombre del paquete",
|
||||
placeholder: "Ej. Paquete Emprendedor",
|
||||
confirmText: "Crear",
|
||||
});
|
||||
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 = await showPrompt({
|
||||
title: "Nueva fase",
|
||||
label: "Nombre de la fase",
|
||||
placeholder: "Ej. Fase 1 - Setup",
|
||||
confirmText: "Agregar",
|
||||
});
|
||||
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) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Eliminar fase",
|
||||
message: "¿Eliminar esta fase?",
|
||||
confirmText: "Eliminar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) 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<CatalogoServicio | 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 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 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 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>}
|
||||
{s.soloAdmin && (
|
||||
<span
|
||||
className="inline-block px-2 py-0.5 rounded text-xs font-medium bg-slate-200 text-slate-700"
|
||||
title="Visible solo para Jareth en la web; oculto para bots y agentes IA"
|
||||
>
|
||||
Solo admin
|
||||
</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 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 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" />
|
||||
</button>
|
||||
<button onClick={async () => {
|
||||
const ok = await showConfirm({ title: "Eliminar servicio", message: `¿Eliminar "${s.nombre}"?`, confirmText: "Eliminar", danger: true });
|
||||
if (!ok) 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); 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" />}
|
||||
<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 table-fixed">
|
||||
<tbody>
|
||||
{fase.servicios.map((s) => (
|
||||
<tr key={s.id} className="border-t border-border">
|
||||
<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 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 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>
|
||||
</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}
|
||||
onSaved={(guardado) => {
|
||||
if (servicioModal) {
|
||||
setServicios((p) => p.map((s) => (s.id === guardado.id ? { ...s, ...guardado } : s)));
|
||||
showToast("Servicio actualizado", "success");
|
||||
} else {
|
||||
setServicios((p) => [...p, guardado]);
|
||||
showToast("Servicio creado", "success");
|
||||
}
|
||||
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 showToast = useToast();
|
||||
|
||||
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(); showToast(e.error, "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: CatalogoServicio[];
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { normalizarPaquetes } from "@/lib/api";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import {
|
||||
CatalogoClient,
|
||||
type CatalogoCategoria,
|
||||
type CatalogoServicio,
|
||||
type PaqueteUI,
|
||||
} from "./CatalogoClient";
|
||||
|
||||
export function CatalogoPage() {
|
||||
const [data, setData] = useState<{
|
||||
servicios: CatalogoServicio[];
|
||||
categorias: CatalogoCategoria[];
|
||||
paquetes: PaqueteUI[];
|
||||
} | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [sRes, cRes, pRes] = await Promise.all([
|
||||
fetch("/api/catalogo", { credentials: "include" }),
|
||||
fetch("/api/categorias", { credentials: "include" }),
|
||||
fetch("/api/paquetes", { credentials: "include" }),
|
||||
]);
|
||||
if (!sRes.ok || !cRes.ok || !pRes.ok) {
|
||||
throw new Error("No se pudo cargar el catálogo");
|
||||
}
|
||||
const [servicios, categorias, rawPaquetes] = await Promise.all([
|
||||
sRes.json(),
|
||||
cRes.json(),
|
||||
pRes.json(),
|
||||
]);
|
||||
setData({
|
||||
servicios,
|
||||
categorias,
|
||||
paquetes: normalizarPaquetes(rawPaquetes),
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return (
|
||||
<CatalogoClient
|
||||
initialServicios={data.servicios}
|
||||
initialCategorias={data.categorias}
|
||||
initialPaquetes={data.paquetes}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
|
||||
export type ClienteEditable = {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
puesto: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
rfc: string | null;
|
||||
};
|
||||
|
||||
type Form = Record<"nombre" | "empresa" | "puesto" | "email" | "telefono" | "rfc", string>;
|
||||
|
||||
const CAMPOS: {
|
||||
clave: keyof Form;
|
||||
etiqueta: string;
|
||||
tipo?: string;
|
||||
placeholder?: string;
|
||||
autoComplete?: string;
|
||||
ancho?: boolean;
|
||||
}[] = [
|
||||
{ clave: "nombre", etiqueta: "Nombre del contacto *", placeholder: "Nombre y apellidos", autoComplete: "off", ancho: true },
|
||||
{ clave: "puesto", etiqueta: "Puesto", placeholder: "Ej. Director", autoComplete: "off" },
|
||||
{ clave: "empresa", etiqueta: "Empresa", placeholder: "Razón o nombre comercial", autoComplete: "off" },
|
||||
{ clave: "email", etiqueta: "Correo", tipo: "email", placeholder: "[email protected]", autoComplete: "off" },
|
||||
{ clave: "telefono", etiqueta: "Teléfono", tipo: "tel", placeholder: "+52 442 123 4567", autoComplete: "off" },
|
||||
{ clave: "rfc", etiqueta: "RFC", placeholder: "Opcional", autoComplete: "off" },
|
||||
];
|
||||
|
||||
export function ClienteDialog({
|
||||
cliente,
|
||||
onClose,
|
||||
onGuardado,
|
||||
}: {
|
||||
cliente: ClienteEditable | null;
|
||||
onClose: () => void;
|
||||
onGuardado: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const [form, setForm] = useState<Form>({
|
||||
nombre: cliente?.nombre ?? "",
|
||||
empresa: cliente?.empresa ?? "",
|
||||
puesto: cliente?.puesto ?? "",
|
||||
email: cliente?.email ?? "",
|
||||
telefono: cliente?.telefono ?? "",
|
||||
rfc: cliente?.rfc ?? "",
|
||||
});
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const guardar = async () => {
|
||||
if (!form.nombre.trim()) {
|
||||
toast("El nombre es requerido", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
try {
|
||||
const res = await fetch(cliente ? `/api/clientes/${cliente.id}` : "/api/clientes", {
|
||||
method: cliente ? "PATCH" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al guardar el cliente", "error");
|
||||
return;
|
||||
}
|
||||
toast(cliente ? "Cliente actualizado" : `${data.nombre} quedó registrado`, "success");
|
||||
onGuardado();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
titulo={cliente ? `Editar a ${cliente.nombre}` : "Nuevo cliente"}
|
||||
descripcion={
|
||||
cliente
|
||||
? undefined
|
||||
: "Regístralo para programarle cobros o tenerlo listo para su próxima cotización."
|
||||
}
|
||||
onClose={onClose}
|
||||
onSubmit={guardar}
|
||||
ancho="max-w-lg"
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={onClose} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : cliente ? "Guardar cambios" : "Agregar cliente"}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{CAMPOS.map((c) => (
|
||||
<div key={c.clave} className={c.ancho ? "sm:col-span-2" : undefined}>
|
||||
<label htmlFor={`cliente-${c.clave}`} className={claseEtiqueta}>
|
||||
{c.etiqueta}
|
||||
</label>
|
||||
<input
|
||||
id={`cliente-${c.clave}`}
|
||||
type={c.tipo ?? "text"}
|
||||
value={form[c.clave]}
|
||||
required={c.clave === "nombre"}
|
||||
autoComplete={c.autoComplete}
|
||||
placeholder={c.placeholder}
|
||||
onChange={(e) => setForm((f) => ({ ...f, [c.clave]: e.target.value }))}
|
||||
className={`${claseCampo}${c.clave === "rfc" ? " uppercase placeholder:normal-case" : ""}`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { KeyRound, Pencil, Search, Trash2, UserPlus, Users } from "lucide-react";
|
||||
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
import { NuevaCotizacionClienteButton } from "./NuevaCotizacionClienteButton";
|
||||
import { ClienteDialog, type ClienteEditable } from "./ClienteDialog";
|
||||
|
||||
export interface Cliente extends ClienteEditable {
|
||||
_count: { cotizaciones: number };
|
||||
usuario: { id: string; email: string } | null;
|
||||
}
|
||||
|
||||
type DialogoAcceso = {
|
||||
cliente: Cliente;
|
||||
modo: "crear" | "rotar";
|
||||
email: string;
|
||||
password: string;
|
||||
} | null;
|
||||
|
||||
type DialogoCliente = Cliente | null | undefined;
|
||||
|
||||
export function ClientesList({
|
||||
clientes,
|
||||
abrirNuevo = false,
|
||||
onRefresh,
|
||||
}: {
|
||||
clientes: Cliente[];
|
||||
abrirNuevo?: boolean;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
const [dialogo, setDialogo] = useState<DialogoAcceso>(null);
|
||||
const [editando, setEditando] = useState<DialogoCliente>(abrirNuevo ? null : undefined);
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const showConfirm = useConfirm();
|
||||
const toast = useToast();
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!search) return clientes;
|
||||
const q = search.toLowerCase();
|
||||
return clientes.filter((c) =>
|
||||
[c.nombre, c.empresa, c.email, c.telefono, c.puesto].some((v) =>
|
||||
(v || "").toLowerCase().includes(q)
|
||||
)
|
||||
);
|
||||
}, [clientes, search]);
|
||||
|
||||
const cerrarCliente = () => {
|
||||
setEditando(undefined);
|
||||
if (abrirNuevo) navigate("/clientes", { replace: true });
|
||||
};
|
||||
|
||||
const clienteGuardado = () => {
|
||||
cerrarCliente();
|
||||
onRefresh();
|
||||
};
|
||||
|
||||
const abrirDialogo = (cliente: Cliente, modo: "crear" | "rotar") => {
|
||||
setDialogo({
|
||||
cliente,
|
||||
modo,
|
||||
email: modo === "rotar" ? cliente.usuario?.email || "" : cliente.email || "",
|
||||
password: "",
|
||||
});
|
||||
};
|
||||
|
||||
const guardarAcceso = async () => {
|
||||
if (!dialogo) return;
|
||||
const email = dialogo.email.trim();
|
||||
const password = dialogo.password;
|
||||
if (!email) {
|
||||
toast("El correo es requerido", "error");
|
||||
return;
|
||||
}
|
||||
if (password.length < 6) {
|
||||
toast("La contraseña debe tener al menos 6 caracteres", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
try {
|
||||
const res = await fetch(`/api/clientes/${dialogo.cliente.id}/acceso`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al guardar acceso", "error");
|
||||
return;
|
||||
}
|
||||
toast(dialogo.modo === "crear" ? "Acceso creado" : "Acceso actualizado", "success");
|
||||
setDialogo(null);
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
const revocarAcceso = async (cliente: Cliente) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Revocar acceso",
|
||||
message: `¿Eliminar la cuenta de panel de ${cliente.nombre}? El cliente dejará de poder iniciar sesión.`,
|
||||
confirmText: "Revocar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/clientes/${cliente.id}/acceso`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al revocar acceso", "error");
|
||||
return;
|
||||
}
|
||||
toast("Acceso revocado", "success");
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="relative w-full max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
||||
<input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Buscar por nombre, empresa, correo o teléfono..."
|
||||
aria-label="Buscar clientes"
|
||||
className="w-full pl-10 pr-3 py-2 border border-border rounded-lg text-sm bg-card-bg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setEditando(null)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-primary hover:opacity-90"
|
||||
>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
Nuevo cliente
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{clientes.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<Users className="w-10 h-10 text-muted mx-auto mb-3" />
|
||||
<h2 className="text-lg font-semibold mb-2">Aún no hay clientes</h2>
|
||||
<p className="text-muted max-w-sm mx-auto">
|
||||
Agrégalos con «Nuevo cliente» o se registrarán solos al guardar su primera cotización.
|
||||
</p>
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<p className="text-center text-muted py-8">Sin resultados para esa búsqueda</p>
|
||||
) : (
|
||||
<div className="relative bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[60rem] 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">Correo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Teléfono</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Cotizaciones</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acceso panel</th>
|
||||
<th className="px-5 py-3">
|
||||
<span className="sr-only">Acciones</span>
|
||||
</th>
|
||||
</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 min-w-[12rem]">
|
||||
<div className="font-medium">{c.nombre}</div>
|
||||
{c.puesto && <div className="text-xs text-muted">{c.puesto}</div>}
|
||||
</td>
|
||||
<td className="px-5 py-3 min-w-[10rem]">{c.empresa || "—"}</td>
|
||||
<td className="px-5 py-3 text-muted">{c.email || "—"}</td>
|
||||
<td className="px-5 py-3 text-muted whitespace-nowrap tabular-nums">
|
||||
{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 tabular-nums">
|
||||
{c._count.cotizaciones}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{c.usuario ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-muted">{c.usuario.email}</span>
|
||||
<button
|
||||
onClick={() => abrirDialogo(c, "rotar")}
|
||||
className="text-xs text-primary hover:underline flex items-center gap-1"
|
||||
>
|
||||
<KeyRound className="w-3 h-3" />
|
||||
Rotar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => revocarAcceso(c)}
|
||||
className="text-xs text-danger hover:underline flex items-center gap-1"
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
Revocar
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => abrirDialogo(c, "crear")}
|
||||
className="px-3 py-1 rounded-lg text-xs font-medium text-primary-dark bg-primary-light/70 hover:bg-primary hover:text-white transition-colors"
|
||||
>
|
||||
Crear acceso
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<button
|
||||
onClick={() => setEditando(c)}
|
||||
className="p-1.5 text-muted hover:text-primary hover:bg-primary/5 rounded transition-colors"
|
||||
title="Editar cliente"
|
||||
aria-label={`Editar a ${c.nombre}`}
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</button>
|
||||
<NuevaCotizacionClienteButton
|
||||
clienteNombre={c.nombre}
|
||||
clienteEmpresa={c.empresa || ""}
|
||||
clienteEmail={c.email || ""}
|
||||
clienteTelefono={c.telefono || ""}
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editando !== undefined && (
|
||||
<ClienteDialog cliente={editando} onClose={cerrarCliente} onGuardado={clienteGuardado} />
|
||||
)}
|
||||
|
||||
{dialogo && (
|
||||
<Modal
|
||||
titulo={
|
||||
dialogo.modo === "crear"
|
||||
? `Crear acceso para ${dialogo.cliente.nombre}`
|
||||
: `Rotar acceso de ${dialogo.cliente.nombre}`
|
||||
}
|
||||
descripcion="Con este correo y contraseña entrará al portal de clientes para ver sus cotizaciones y pagos."
|
||||
onClose={() => setDialogo(null)}
|
||||
onSubmit={guardarAcceso}
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={() => setDialogo(null)} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : "Guardar"}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="acceso-email" className={claseEtiqueta}>
|
||||
Correo
|
||||
</label>
|
||||
<input
|
||||
id="acceso-email"
|
||||
type="email"
|
||||
value={dialogo.email}
|
||||
autoComplete="off"
|
||||
onChange={(e) => setDialogo((d) => (d ? { ...d, email: e.target.value } : d))}
|
||||
className={claseCampo}
|
||||
placeholder="[email protected]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="acceso-password" className={claseEtiqueta}>
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
id="acceso-password"
|
||||
type="password"
|
||||
value={dialogo.password}
|
||||
autoComplete="new-password"
|
||||
onChange={(e) => setDialogo((d) => (d ? { ...d, password: e.target.value } : d))}
|
||||
className={claseCampo}
|
||||
placeholder="Mínimo 6 caracteres"
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { ClientesList, type Cliente } from "./ClientesList";
|
||||
|
||||
export function ClientesPage() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const abrirNuevo = searchParams.get("nuevo") === "1";
|
||||
const [clientes, setClientes] = useState<Cliente[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/clientes", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudieron cargar los clientes");
|
||||
setClientes(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !clientes) return <LoadingScreen />;
|
||||
if (error || !clientes) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Clientes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{clientes.length === 1 ? "1 cliente registrado" : `${clientes.length} clientes registrados`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ClientesList clientes={clientes} abrirNuevo={abrirNuevo} onRefresh={load} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { useState, useRef } from "react";
|
||||
import { Save, Upload, Trash2, Loader2, Image as ImageIcon } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
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 (opcional, uso interno)", type: "text", hint: "Solo referencia interna. No se imprime en cotizaciones, PDF ni Excel." },
|
||||
],
|
||||
},
|
||||
{
|
||||
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 showToast = useToast();
|
||||
|
||||
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) {
|
||||
showToast("El logo debe ser menor a 500KB", "error");
|
||||
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 {
|
||||
showToast("Error al guardar", "error");
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al guardar", "error");
|
||||
} 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"
|
||||
/>
|
||||
) : (
|
||||
<ImageIcon 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] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4")}
|
||||
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] || (field.key === "color_secundario" ? "#0F172A" : "#0400C4") }}
|
||||
/>
|
||||
</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"
|
||||
/>
|
||||
)}
|
||||
{"hint" in field && field.hint && (
|
||||
<p className="text-xs text-muted mt-1">{field.hint}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { ConfiguracionClient } from "./ConfiguracionClient";
|
||||
|
||||
export function ConfiguracionPage() {
|
||||
const [config, setConfig] = useState<Record<string, string> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/configuracion", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudo cargar la configuración");
|
||||
setConfig(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !config) return <LoadingScreen />;
|
||||
if (error || !config) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return <ConfiguracionClient initial={config} />;
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { FileText, Plus, Users, Database } from "lucide-react";
|
||||
import { formatCurrency, formatDate } from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
|
||||
interface DashboardCotizacion {
|
||||
id: string;
|
||||
numero: string;
|
||||
fecha: string;
|
||||
estado: string;
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
servicios: { tipoPago: string; seleccionado: boolean; precio: number }[];
|
||||
}
|
||||
|
||||
interface DashboardData {
|
||||
totalCotizaciones: number;
|
||||
totalClientes: number;
|
||||
totalServicios: number;
|
||||
cotizacionesRecientes: DashboardCotizacion[];
|
||||
}
|
||||
|
||||
export function DashboardPage() {
|
||||
const [data, setData] = useState<DashboardData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/dashboard", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudo cargar el dashboard");
|
||||
const json: DashboardData = await res.json();
|
||||
setData(json);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
const stats = [
|
||||
{
|
||||
label: "Cotizaciones",
|
||||
value: data.totalCotizaciones,
|
||||
icon: FileText,
|
||||
color: "text-primary",
|
||||
bg: "bg-primary-light",
|
||||
},
|
||||
{
|
||||
label: "Clientes",
|
||||
value: data.totalClientes,
|
||||
icon: Users,
|
||||
color: "text-secondary",
|
||||
bg: "bg-slate-100",
|
||||
},
|
||||
{
|
||||
label: "Servicios Activos",
|
||||
value: data.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 — Uriel Jareth Consulting
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/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>
|
||||
{data.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
|
||||
to="/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>
|
||||
{data.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
|
||||
to={`/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(new Date(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,38 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
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 navigate = useNavigate();
|
||||
const store = useCotizacionStore();
|
||||
|
||||
const handleClick = () => {
|
||||
store.resetDraft();
|
||||
store.setField("clienteNombre", clienteNombre);
|
||||
store.setField("clienteEmpresa", clienteEmpresa);
|
||||
store.setField("clienteEmail", clienteEmail);
|
||||
store.setField("clienteTelefono", clienteTelefono);
|
||||
navigate("/cotizaciones/nueva");
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className="p-1.5 text-muted hover:text-primary hover:bg-primary/5 rounded transition-colors"
|
||||
title="Nueva cotización"
|
||||
aria-label={`Nueva cotización para ${clienteNombre}`}
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { useConfirm, usePrompt, useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||
import { ProgramasTabla } from "./ProgramasTabla";
|
||||
import { PagosTabla } from "./PagosTabla";
|
||||
import { PorCobrarTabla } from "./PorCobrarTabla";
|
||||
import { RegistrarPagoDialog } from "./RegistrarPagoDialog";
|
||||
import type {
|
||||
ProgramaRow,
|
||||
ClienteOpt,
|
||||
PagoRow,
|
||||
SaldoClienteRow,
|
||||
ResultadoRecordatorioRow,
|
||||
} from "./types";
|
||||
|
||||
export function frecuenciaLegible(p: {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
}): string {
|
||||
const dias = [
|
||||
"domingo",
|
||||
"lunes",
|
||||
"martes",
|
||||
"miércoles",
|
||||
"jueves",
|
||||
"viernes",
|
||||
"sábado",
|
||||
];
|
||||
if (p.frecuencia === "semanal") {
|
||||
const d = p.diaSemana ?? 0;
|
||||
return `Cada ${dias[d]}`;
|
||||
}
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada día ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
function motivoNoEntregado(
|
||||
r: ResultadoRecordatorioRow,
|
||||
canales: { correo: boolean; push: boolean }
|
||||
): string {
|
||||
if (!canales.correo && !canales.push) {
|
||||
return "No hay SMTP (correo) ni VAPID (push) configurados en el servidor";
|
||||
}
|
||||
if (r.correo === "error") return "Falló el envío del correo; revisa el log del servidor";
|
||||
if (r.correo === "sin_email") {
|
||||
return "El cliente no tiene correo y no activó los avisos push";
|
||||
}
|
||||
if (r.correo === "omitido") {
|
||||
return "SMTP no configurado y el cliente no activó los avisos push";
|
||||
}
|
||||
return "No se pudo entregar por ningún canal";
|
||||
}
|
||||
|
||||
export function CobrosClient({
|
||||
programas,
|
||||
clientes,
|
||||
pagosIniciales,
|
||||
saldos,
|
||||
diasRecordatorio,
|
||||
enRevision,
|
||||
onRefresh,
|
||||
}: {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
pagosIniciales: PagoRow[];
|
||||
saldos: SaldoClienteRow[];
|
||||
diasRecordatorio: number;
|
||||
enRevision: number;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const showConfirm = useConfirm();
|
||||
const showPrompt = usePrompt();
|
||||
const toast = useToast();
|
||||
|
||||
const cargadoInicial = useRef(false);
|
||||
const [pagos, setPagos] = useState<PagoRow[]>(pagosIniciales);
|
||||
const [cargandoPagos, setCargandoPagos] = useState(false);
|
||||
const [estadoFiltro, setEstadoFiltro] = useState("en_revision");
|
||||
const [clienteFiltro, setClienteFiltro] = useState("");
|
||||
const [desdeFiltro, setDesdeFiltro] = useState("");
|
||||
const [hastaFiltro, setHastaFiltro] = useState("");
|
||||
const [enviandoRecordatorio, setEnviandoRecordatorio] = useState<string | null>(null);
|
||||
const [registrando, setRegistrando] = useState<PagoRow | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
estadoFiltro === "en_revision" &&
|
||||
!clienteFiltro &&
|
||||
!desdeFiltro &&
|
||||
!hastaFiltro
|
||||
) {
|
||||
setPagos(pagosIniciales);
|
||||
}
|
||||
}, [pagosIniciales, estadoFiltro, clienteFiltro, desdeFiltro, hastaFiltro]);
|
||||
|
||||
const cargarPagos = useCallback(async () => {
|
||||
setCargandoPagos(true);
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
if (estadoFiltro) params.set("estado", estadoFiltro);
|
||||
if (clienteFiltro) params.set("clienteId", clienteFiltro);
|
||||
if (desdeFiltro) params.set("desde", desdeFiltro);
|
||||
if (hastaFiltro) params.set("hasta", hastaFiltro);
|
||||
const res = await fetch(`/api/cobros/pagos?${params.toString()}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setPagos(Array.isArray(data) ? data : []);
|
||||
}
|
||||
} catch {
|
||||
// silencioso: la tabla queda vacia
|
||||
} finally {
|
||||
setCargandoPagos(false);
|
||||
}
|
||||
}, [estadoFiltro, clienteFiltro, desdeFiltro, hastaFiltro]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!cargadoInicial.current) {
|
||||
cargadoInicial.current = true;
|
||||
return;
|
||||
}
|
||||
cargarPagos();
|
||||
}, [cargarPagos]);
|
||||
|
||||
const generarAhora = async () => {
|
||||
const ok = await showConfirm({
|
||||
title: "Generar cobros",
|
||||
message:
|
||||
"Se generarán los cobros pendientes de todos los programas activos hasta hoy. ¿Continuar?",
|
||||
confirmText: "Generar",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch("/api/cobros/generar", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al generar cobros", "error");
|
||||
return;
|
||||
}
|
||||
const n = data.generados ?? 0;
|
||||
toast(
|
||||
n > 0 ? `Se generaron ${n} cobros` : "No había cobros pendientes",
|
||||
"success"
|
||||
);
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const recordar = async (saldo: SaldoClienteRow | null) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Enviar recordatorio de pago",
|
||||
message: saldo
|
||||
? `Se enviará a ${saldo.nombre} su estado de cuenta: ${saldo.pagos} ${saldo.pagos === 1 ? "cobro pendiente" : "cobros pendientes"} por ${formatTotales(saldo.totales)}, por correo y aviso push.`
|
||||
: `Se enviará el estado de cuenta a ${saldos.length} ${saldos.length === 1 ? "cliente" : "clientes"} con pagos vencidos, por correo y aviso push.`,
|
||||
confirmText: "Enviar",
|
||||
});
|
||||
if (!ok) return;
|
||||
setEnviandoRecordatorio(saldo?.clienteId ?? "*");
|
||||
try {
|
||||
const res = await fetch("/api/cobros/recordatorios", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(saldo ? { clienteId: saldo.clienteId } : {}),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al enviar el recordatorio", "error");
|
||||
return;
|
||||
}
|
||||
const resultados: ResultadoRecordatorioRow[] = data.resultados ?? [];
|
||||
const canales = data.canales ?? { correo: false, push: false };
|
||||
const entregados = resultados.filter((r) => r.entregado);
|
||||
if (resultados.length === 0) {
|
||||
toast("No hay pagos vencidos por recordar", "info");
|
||||
} else if (entregados.length === resultados.length) {
|
||||
toast(
|
||||
entregados.length === 1
|
||||
? `Recordatorio enviado a ${entregados[0].cliente}`
|
||||
: `Recordatorio enviado a ${entregados.length} clientes`,
|
||||
"success"
|
||||
);
|
||||
} else if (entregados.length > 0) {
|
||||
const fallidos = resultados.filter((r) => !r.entregado).map((r) => r.cliente);
|
||||
toast(
|
||||
`Enviado a ${entregados.length} de ${resultados.length}. Sin entregar: ${fallidos.join(", ")}`,
|
||||
"info"
|
||||
);
|
||||
} else {
|
||||
toast(
|
||||
resultados.length === 1
|
||||
? `No se envió: ${motivoNoEntregado(resultados[0], canales)}`
|
||||
: `No se envió a ningún cliente: ${motivoNoEntregado(resultados[0], canales)}`,
|
||||
"error"
|
||||
);
|
||||
}
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setEnviandoRecordatorio(null);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActivo = async (p: ProgramaRow) => {
|
||||
const activar = !p.activo;
|
||||
const ok = await showConfirm({
|
||||
title: activar ? "Activar programa" : "Desactivar programa",
|
||||
message: activar
|
||||
? `¿Activar el programa "${p.concepto}"? Se generarán cobros en sus próximos periodos.`
|
||||
: `¿Desactivar el programa "${p.concepto}"? No se generarán más cobros, pero los existentes se conservan.`,
|
||||
confirmText: activar ? "Activar" : "Desactivar",
|
||||
danger: !activar,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/programas/${p.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ activo: activar }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al actualizar", "error");
|
||||
return;
|
||||
}
|
||||
toast(activar ? "Programa activado" : "Programa desactivado", "success");
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const aprobar = async (pago: PagoRow) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Aprobar comprobante",
|
||||
message: `Marcar el cobro del ${formatFechaCorta(new Date(pago.fecha))} como verificado?`,
|
||||
confirmText: "Aprobar",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/aprobar`, {
|
||||
method: "POST",
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al aprobar", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro verificado", "success");
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const rechazar = async (pago: PagoRow) => {
|
||||
const motivo = await showPrompt({
|
||||
title: "Rechazar comprobante",
|
||||
label: "Motivo del rechazo (opcional)",
|
||||
placeholder: "Ej. ilegible, monto incorrecto...",
|
||||
confirmText: "Rechazar",
|
||||
});
|
||||
if (motivo === null) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/rechazar`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ motivo: motivo.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al rechazar", "error");
|
||||
return;
|
||||
}
|
||||
toast("Comprobante rechazado", "success");
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const verPorPagar = (saldo: SaldoClienteRow) => {
|
||||
setClienteFiltro(saldo.clienteId);
|
||||
setEstadoFiltro("por_pagar");
|
||||
setDesdeFiltro("");
|
||||
setHastaFiltro("");
|
||||
document.getElementById("comprobantes")?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
};
|
||||
|
||||
const alRegistrar = () => {
|
||||
setRegistrando(null);
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
};
|
||||
|
||||
const anular = async (pago: PagoRow) => {
|
||||
const motivo = await showPrompt({
|
||||
title: "Anular cobro",
|
||||
message: `El cobro del ${formatFechaCorta(new Date(pago.fecha))} de ${pago.programa.cliente.nombre} quedará sin cargo y dejará de contar como adeudo. Puedes reabrirlo después.`,
|
||||
label: "Motivo",
|
||||
placeholder: "Ej. semana sin servicio, cortesía...",
|
||||
confirmText: "Anular cobro",
|
||||
});
|
||||
if (motivo === null) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/anular`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ motivo: motivo.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al anular", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro anulado", "success");
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const reabrir = async (pago: PagoRow) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Reabrir cobro",
|
||||
message:
|
||||
pago.estado === "anulado"
|
||||
? `El cobro del ${formatFechaCorta(new Date(pago.fecha))} volverá a pendiente y contará otra vez como adeudo.`
|
||||
: `Se quitará el pago registrado del ${formatFechaCorta(new Date(pago.fecha))} y el cobro volverá a pendiente.`,
|
||||
confirmText: "Reabrir",
|
||||
danger: pago.estado !== "anulado",
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/reabrir`, { method: "POST" });
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al reabrir", "error");
|
||||
return;
|
||||
}
|
||||
toast("Cobro reabierto", "success");
|
||||
cargarPagos();
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
}
|
||||
};
|
||||
|
||||
const totalPorCobrar: Record<string, number> = {};
|
||||
for (const s of saldos) {
|
||||
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||
totalPorCobrar[moneda] = (totalPorCobrar[moneda] ?? 0) + total;
|
||||
}
|
||||
}
|
||||
const programasActivos = programas.filter((p) => p.activo).length;
|
||||
const resumen = [
|
||||
{
|
||||
href: "#por-cobrar",
|
||||
label: "Por cobrar",
|
||||
valor: saldos.length ? formatTotales(totalPorCobrar) : "$0",
|
||||
detalle: saldos.length
|
||||
? `${saldos.length} ${saldos.length === 1 ? "cliente con adeudo" : "clientes con adeudo"}`
|
||||
: "Nadie tiene pagos vencidos",
|
||||
alerta: saldos.length > 0,
|
||||
},
|
||||
{
|
||||
href: "#comprobantes",
|
||||
label: "Comprobantes por revisar",
|
||||
valor: String(enRevision),
|
||||
detalle: enRevision ? "Esperan tu aprobación" : "Todo revisado",
|
||||
alerta: enRevision > 0,
|
||||
},
|
||||
{
|
||||
href: "#programas",
|
||||
label: "Programas activos",
|
||||
valor: String(programasActivos),
|
||||
detalle: `${programas.length - programasActivos} inactivos`,
|
||||
alerta: false,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-10">
|
||||
<nav
|
||||
aria-label="Resumen de cobros"
|
||||
className="grid grid-cols-1 sm:grid-cols-3 bg-card-bg rounded-xl border border-border divide-y sm:divide-y-0 sm:divide-x divide-border overflow-hidden"
|
||||
>
|
||||
{resumen.map((r) => (
|
||||
<a key={r.href} href={r.href} className="block px-5 py-4 hover:bg-gray-50 transition-colors">
|
||||
<p className="text-xs font-medium text-muted">{r.label}</p>
|
||||
<p className={`text-xl font-semibold tracking-tight tabular-nums mt-1 ${r.alerta ? "text-foreground" : "text-muted"}`}>
|
||||
{r.valor}
|
||||
</p>
|
||||
<p className={`text-xs mt-0.5 ${r.alerta ? "text-amber-700" : "text-muted"}`}>{r.detalle}</p>
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<section id="por-cobrar" className="scroll-mt-20">
|
||||
<PorCobrarTabla
|
||||
saldos={saldos}
|
||||
diasRecordatorio={diasRecordatorio}
|
||||
enviando={enviandoRecordatorio}
|
||||
onRecordar={recordar}
|
||||
onVerPorPagar={verPorPagar}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section id="comprobantes" className="scroll-mt-20">
|
||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Comprobantes y cobros</h2>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Aprueba los comprobantes que suben tus clientes, registra los pagos que recibes por
|
||||
fuera del panel y consulta cualquier cobro.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={generarAhora}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
Generar cobros ahora
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-3 mb-4">
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Estado</label>
|
||||
<select
|
||||
value={estadoFiltro}
|
||||
onChange={(e) => setEstadoFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="por_pagar">Por pagar (pendiente o rechazado)</option>
|
||||
<option value="pendiente">Pendiente</option>
|
||||
<option value="en_revision">En revisión</option>
|
||||
<option value="verificado">Verificado</option>
|
||||
<option value="rechazado">Rechazado</option>
|
||||
<option value="anulado">Anulado</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Cliente</label>
|
||||
<select
|
||||
value={clienteFiltro}
|
||||
onChange={(e) => setClienteFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{clientes.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.empresa ? `${c.nombre} — ${c.empresa}` : c.nombre}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Desde</label>
|
||||
<input
|
||||
type="date"
|
||||
value={desdeFiltro}
|
||||
onChange={(e) => setDesdeFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Hasta</label>
|
||||
<input
|
||||
type="date"
|
||||
value={hastaFiltro}
|
||||
onChange={(e) => setHastaFiltro(e.target.value)}
|
||||
className="px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PagosTabla
|
||||
pagos={pagos}
|
||||
cargando={cargandoPagos}
|
||||
onAprobar={aprobar}
|
||||
onRechazar={rechazar}
|
||||
onRegistrar={setRegistrando}
|
||||
onAnular={anular}
|
||||
onReabrir={reabrir}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section id="programas" className="scroll-mt-20">
|
||||
<ProgramasTabla
|
||||
programas={programas}
|
||||
clientes={clientes}
|
||||
onToggleActivo={toggleActivo}
|
||||
onRefresh={onRefresh}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{registrando && (
|
||||
<RegistrarPagoDialog
|
||||
pago={registrando}
|
||||
onClose={() => setRegistrando(null)}
|
||||
onRegistrado={alRegistrar}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { CobrosClient } from "./CobrosClient";
|
||||
import type { ClienteOpt, PagoRow, ProgramaRow, SaldoClienteRow } from "./types";
|
||||
|
||||
interface CobrosResumenData {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
pagosEnRevision: PagoRow[];
|
||||
saldos: SaldoClienteRow[];
|
||||
diasRecordatorio: number;
|
||||
}
|
||||
|
||||
export function CobrosPage() {
|
||||
const [data, setData] = useState<CobrosResumenData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/cobros/resumen", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudieron cargar los cobros");
|
||||
setData(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Cobros recurrentes</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Cobra a tiempo, revisa comprobantes y programa cobros periódicos
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<CobrosClient
|
||||
programas={data.programas}
|
||||
clientes={data.clientes}
|
||||
pagosIniciales={data.pagosEnRevision}
|
||||
saldos={data.saldos}
|
||||
diasRecordatorio={data.diasRecordatorio}
|
||||
enRevision={data.pagosEnRevision.length}
|
||||
onRefresh={load}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ESTADOS_PAGO } from "@/lib/cobros-fechas";
|
||||
|
||||
const ESTILOS: Record<string, { cls: string; label: string }> = {
|
||||
[ESTADOS_PAGO.PENDIENTE]: {
|
||||
cls: "bg-amber-100 text-amber-800",
|
||||
label: "Pendiente",
|
||||
},
|
||||
[ESTADOS_PAGO.EN_REVISION]: {
|
||||
cls: "bg-blue-100 text-blue-800",
|
||||
label: "En revisión",
|
||||
},
|
||||
[ESTADOS_PAGO.VERIFICADO]: {
|
||||
cls: "bg-green-100 text-green-800",
|
||||
label: "Verificado",
|
||||
},
|
||||
[ESTADOS_PAGO.RECHAZADO]: {
|
||||
cls: "bg-red-100 text-red-800",
|
||||
label: "Rechazado",
|
||||
},
|
||||
[ESTADOS_PAGO.ANULADO]: {
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
label: "Anulado",
|
||||
},
|
||||
};
|
||||
|
||||
export function EstadoPagoBadge({ estado }: { estado: string }) {
|
||||
const s = ESTILOS[estado] ?? {
|
||||
cls: "bg-gray-100 text-gray-700",
|
||||
label: estado,
|
||||
};
|
||||
return (
|
||||
<span
|
||||
className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${s.cls}`}
|
||||
>
|
||||
{s.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Ban, Check, FileText, HandCoins, RotateCcw, X } from "lucide-react";
|
||||
import { calendarioDe, esPorPagar, formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||
import { EstadoPagoBadge } from "./EstadoPagoBadge";
|
||||
import type { PagoRow } from "./types";
|
||||
|
||||
const claseAccion = "text-xs hover:underline flex items-center gap-1 whitespace-nowrap";
|
||||
|
||||
function DetalleEstado({ p }: { p: PagoRow }) {
|
||||
const lineas: string[] = [];
|
||||
if (p.estado === "rechazado" && p.rechazoMotivo) lineas.push(p.rechazoMotivo);
|
||||
if (p.estado === "verificado" && p.verificadoAt) {
|
||||
const dia = formatFechaCorta(calendarioDe(new Date(p.verificadoAt)));
|
||||
lineas.push(p.comprobante ? `Aprobado el ${dia}` : `Pagado el ${dia}`);
|
||||
}
|
||||
if (p.nota) lineas.push(p.nota);
|
||||
if (lineas.length === 0) return null;
|
||||
return (
|
||||
<div className="mt-1 max-w-[16rem] space-y-0.5 text-xs text-muted">
|
||||
{lineas.map((l, i) => (
|
||||
<p key={i} className="line-clamp-2" title={l}>
|
||||
{l}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PagosTabla({
|
||||
pagos,
|
||||
cargando,
|
||||
onAprobar,
|
||||
onRechazar,
|
||||
onRegistrar,
|
||||
onAnular,
|
||||
onReabrir,
|
||||
}: {
|
||||
pagos: PagoRow[];
|
||||
cargando: boolean;
|
||||
onAprobar: (p: PagoRow) => void;
|
||||
onRechazar: (p: PagoRow) => void;
|
||||
onRegistrar: (p: PagoRow) => void;
|
||||
onAnular: (p: PagoRow) => void;
|
||||
onReabrir: (p: PagoRow) => void;
|
||||
}) {
|
||||
if (cargando) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<p className="text-muted">Cargando cobros...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (pagos.length === 0) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">No hay cobros</h3>
|
||||
<p className="text-muted">Ajusta los filtros para ver otros cobros.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[56rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<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">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Comprobante</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pagos.map((p) => {
|
||||
const manual = p.estado === "verificado" && !p.comprobante;
|
||||
return (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50 align-top">
|
||||
<td className="px-5 py-3 whitespace-nowrap">{formatFechaCorta(new Date(p.fecha))}</td>
|
||||
<td className="px-5 py-3">{p.programa.concepto}</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{p.programa.cliente.nombre}</div>
|
||||
{p.programa.cliente.empresa && (
|
||||
<div className="text-xs text-muted">{p.programa.cliente.empresa}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right whitespace-nowrap">
|
||||
{formatMonto(p.monto, p.programa.moneda)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<EstadoPagoBadge estado={p.estado} />
|
||||
<DetalleEstado p={p} />
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
{p.comprobante ? (
|
||||
<a
|
||||
href={`/api/comprobantes/${p.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline"
|
||||
>
|
||||
<FileText className="w-3 h-3" />
|
||||
Ver
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted text-xs">{manual ? "Registro manual" : "—"}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.estado === "en_revision" ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={() => onAprobar(p)} className={`${claseAccion} text-success`}>
|
||||
<Check className="w-3 h-3" />
|
||||
Aprobar
|
||||
</button>
|
||||
<button onClick={() => onRechazar(p)} className={`${claseAccion} text-danger`}>
|
||||
<X className="w-3 h-3" />
|
||||
Rechazar
|
||||
</button>
|
||||
</div>
|
||||
) : esPorPagar(p.estado) ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<button onClick={() => onRegistrar(p)} className={`${claseAccion} text-primary`}>
|
||||
<HandCoins className="w-3 h-3" />
|
||||
Registrar pago
|
||||
</button>
|
||||
<button onClick={() => onAnular(p)} className={`${claseAccion} text-muted`}>
|
||||
<Ban className="w-3 h-3" />
|
||||
Anular
|
||||
</button>
|
||||
</div>
|
||||
) : manual || p.estado === "anulado" ? (
|
||||
<button
|
||||
onClick={() => onReabrir(p)}
|
||||
className={`${claseAccion} text-muted`}
|
||||
title="Devolver el cobro a pendiente"
|
||||
>
|
||||
<RotateCcw className="w-3 h-3" />
|
||||
Reabrir
|
||||
</button>
|
||||
) : (
|
||||
<span className="text-muted text-xs">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { BellRing, HandCoins, Send } from "lucide-react";
|
||||
import { formatFechaCorta, formatTotales } from "@/lib/cobros-fechas";
|
||||
import type { SaldoClienteRow } from "./types";
|
||||
|
||||
export function PorCobrarTabla({
|
||||
saldos,
|
||||
diasRecordatorio,
|
||||
enviando,
|
||||
onRecordar,
|
||||
onVerPorPagar,
|
||||
}: {
|
||||
saldos: SaldoClienteRow[];
|
||||
diasRecordatorio: number;
|
||||
enviando: string | null;
|
||||
onRecordar: (saldo: SaldoClienteRow | null) => void;
|
||||
onVerPorPagar: (saldo: SaldoClienteRow) => void;
|
||||
}) {
|
||||
const totalGeneral: Record<string, number> = {};
|
||||
for (const s of saldos) {
|
||||
for (const [moneda, total] of Object.entries(s.totales)) {
|
||||
totalGeneral[moneda] = (totalGeneral[moneda] ?? 0) + total;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-end justify-between gap-3 mb-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold">Pagos por cobrar</h2>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{diasRecordatorio > 0
|
||||
? `Cobros vencidos sin pago o con comprobante rechazado. El recordatorio se reenvía solo cada ${diasRecordatorio} ${diasRecordatorio === 1 ? "día" : "días"} a partir de las 9:00.`
|
||||
: "Cobros vencidos sin pago o con comprobante rechazado. El recordatorio automático está desactivado (COBROS_RECORDATORIO_DIAS=0)."}
|
||||
</p>
|
||||
</div>
|
||||
{saldos.length > 0 && (
|
||||
<button
|
||||
onClick={() => onRecordar(null)}
|
||||
disabled={enviando !== null}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border border-border bg-card-bg hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<BellRing className="w-4 h-4" />
|
||||
{enviando === "*" ? "Enviando..." : "Recordar a todos"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{saldos.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">Sin pagos vencidos</h3>
|
||||
<p className="text-muted">Ningún cliente tiene cobros pendientes de pago.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[54rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Cobros</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Adeudo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Más antiguo</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Último recordatorio</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{saldos.map((s) => (
|
||||
<tr key={s.clienteId} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3">
|
||||
<div className="font-medium">{s.nombre}</div>
|
||||
{s.empresa && <div className="text-xs text-muted">{s.empresa}</div>}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">{s.pagos}</td>
|
||||
<td className="px-5 py-3 text-right font-medium whitespace-nowrap">
|
||||
{formatTotales(s.totales)}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{formatFechaCorta(new Date(s.masAntigua))}</div>
|
||||
<div className={`text-xs ${s.diasAtraso > 0 ? "text-danger" : "text-muted"}`}>
|
||||
{s.diasAtraso === 0
|
||||
? "vence hoy"
|
||||
: `${s.diasAtraso} ${s.diasAtraso === 1 ? "día" : "días"} de atraso`}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-5 py-3 text-muted">
|
||||
{s.ultimoRecordatorio
|
||||
? formatFechaCorta(new Date(s.ultimoRecordatorio))
|
||||
: "Nunca"}
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<button
|
||||
onClick={() => onVerPorPagar(s)}
|
||||
title="Ver sus cobros por pagar para registrar los pagos recibidos"
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline whitespace-nowrap"
|
||||
>
|
||||
<HandCoins className="w-3 h-3" />
|
||||
Registrar pagos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onRecordar(s)}
|
||||
disabled={enviando !== null || !s.contactable}
|
||||
title={
|
||||
s.contactable
|
||||
? "Enviar estado de cuenta por correo y push"
|
||||
: "El cliente no tiene correo ni cuenta de panel"
|
||||
}
|
||||
className="inline-flex items-center gap-1 text-xs text-primary hover:underline whitespace-nowrap disabled:opacity-40 disabled:no-underline disabled:cursor-not-allowed"
|
||||
>
|
||||
<Send className="w-3 h-3" />
|
||||
{enviando === s.clienteId ? "Enviando..." : "Enviar recordatorio"}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="bg-gray-50">
|
||||
<td className="px-5 py-3 font-medium" colSpan={2}>
|
||||
Total por cobrar
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-semibold whitespace-nowrap">
|
||||
{formatTotales(totalGeneral)}
|
||||
</td>
|
||||
<td colSpan={3} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Pencil, Power, Plus } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import { formatFechaCorta, formatMonto } from "@/lib/cobros-fechas";
|
||||
import type { ProgramaRow, ClienteOpt } from "./types";
|
||||
|
||||
const DIAS = [
|
||||
"Domingo",
|
||||
"Lunes",
|
||||
"Martes",
|
||||
"Miércoles",
|
||||
"Jueves",
|
||||
"Viernes",
|
||||
"Sábado",
|
||||
];
|
||||
|
||||
function frecuenciaTexto(p: {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
}): string {
|
||||
if (p.frecuencia === "semanal") return `Cada ${DIAS[p.diaSemana ?? 0]}`;
|
||||
if (p.frecuencia === "quincenal") return "Cada 1 y 15";
|
||||
return `Cada día ${p.diaMes ?? 1}`;
|
||||
}
|
||||
|
||||
function EstadoProgramaBadge({ activo }: { activo: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${
|
||||
activo ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-700"
|
||||
}`}
|
||||
>
|
||||
{activo ? "Activo" : "Inactivo"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
type FormEstado = {
|
||||
concepto: string;
|
||||
monto: string;
|
||||
frecuencia: string;
|
||||
diaSemana: string;
|
||||
diaMes: string;
|
||||
fechaInicio: string;
|
||||
fechaFin: string;
|
||||
};
|
||||
|
||||
type DialogoState = null | "nuevo" | ProgramaRow;
|
||||
|
||||
const FORM_VACIO: FormEstado = {
|
||||
concepto: "",
|
||||
monto: "",
|
||||
frecuencia: "mensual",
|
||||
diaSemana: "1",
|
||||
diaMes: "1",
|
||||
fechaInicio: "",
|
||||
fechaFin: "",
|
||||
};
|
||||
|
||||
export function ProgramasTabla({
|
||||
programas,
|
||||
clientes,
|
||||
onToggleActivo,
|
||||
onRefresh,
|
||||
}: {
|
||||
programas: ProgramaRow[];
|
||||
clientes: ClienteOpt[];
|
||||
onToggleActivo: (p: ProgramaRow) => void;
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const [dialogo, setDialogo] = useState<DialogoState>(null);
|
||||
const [clienteId, setClienteId] = useState("");
|
||||
const [form, setForm] = useState<FormEstado>(FORM_VACIO);
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const abrirNuevo = () => {
|
||||
setClienteId(clientes[0]?.id ?? "");
|
||||
setForm(FORM_VACIO);
|
||||
setDialogo("nuevo");
|
||||
};
|
||||
|
||||
const abrirEditar = (p: ProgramaRow) => {
|
||||
setClienteId(p.cliente.id);
|
||||
setForm({
|
||||
concepto: p.concepto,
|
||||
monto: String(p.monto),
|
||||
frecuencia: p.frecuencia,
|
||||
diaSemana: String(p.diaSemana ?? 0),
|
||||
diaMes: String(p.diaMes ?? 1),
|
||||
fechaInicio: p.fechaInicio.slice(0, 10),
|
||||
fechaFin: p.fechaFin ? p.fechaFin.slice(0, 10) : "",
|
||||
});
|
||||
setDialogo(p);
|
||||
};
|
||||
|
||||
const set = (k: keyof FormEstado, v: string) =>
|
||||
setForm((f) => ({ ...f, [k]: v }));
|
||||
|
||||
const guardar = async () => {
|
||||
if (!form.concepto.trim()) {
|
||||
toast("El concepto es requerido", "error");
|
||||
return;
|
||||
}
|
||||
const monto = parseFloat(form.monto);
|
||||
if (!form.monto || isNaN(monto) || monto <= 0) {
|
||||
toast("El monto debe ser mayor a 0", "error");
|
||||
return;
|
||||
}
|
||||
if (!form.fechaInicio) {
|
||||
toast("La fecha de inicio es requerida", "error");
|
||||
return;
|
||||
}
|
||||
if (dialogo === "nuevo" && !clienteId) {
|
||||
toast("Selecciona un cliente", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
concepto: form.concepto.trim(),
|
||||
monto,
|
||||
frecuencia: form.frecuencia,
|
||||
fechaInicio: form.fechaInicio,
|
||||
};
|
||||
if (form.frecuencia === "semanal") payload.diaSemana = parseInt(form.diaSemana, 10);
|
||||
if (form.frecuencia === "mensual") payload.diaMes = parseInt(form.diaMes, 10);
|
||||
if (form.fechaFin) payload.fechaFin = form.fechaFin;
|
||||
|
||||
setGuardando(true);
|
||||
try {
|
||||
const actual = dialogo as NonNullable<DialogoState>;
|
||||
const esNuevo = actual === "nuevo";
|
||||
const url = esNuevo
|
||||
? "/api/cobros/programas"
|
||||
: `/api/cobros/programas/${actual.id}`;
|
||||
const method = esNuevo ? "POST" : "PATCH";
|
||||
const body = esNuevo ? { ...payload, clienteId } : payload;
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al guardar", "error");
|
||||
return;
|
||||
}
|
||||
toast(esNuevo ? "Programa creado" : "Programa actualizado", "success");
|
||||
setDialogo(null);
|
||||
onRefresh();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<h2 className="text-lg font-semibold">Programas de pago</h2>
|
||||
<button
|
||||
onClick={abrirNuevo}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
Nuevo programa
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{programas.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">No hay programas de pago</h3>
|
||||
<p className="text-muted">
|
||||
Crea un programa para empezar a generar cobros recurrentes
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-x-auto">
|
||||
<table className="w-full min-w-[56rem] text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Concepto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Cliente</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Monto</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Frecuencia</th>
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Próximo cobro</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Estado</th>
|
||||
<th className="text-center px-5 py-3 font-medium text-muted">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{programas.map((p) => (
|
||||
<tr key={p.id} className="border-b border-border hover:bg-gray-50">
|
||||
<td className="px-5 py-3 font-medium">{p.concepto}</td>
|
||||
<td className="px-5 py-3">
|
||||
<div>{p.cliente.nombre}</div>
|
||||
{p.cliente.empresa && (
|
||||
<div className="text-xs text-muted">{p.cliente.empresa}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right">{formatMonto(p.monto, p.moneda)}</td>
|
||||
<td className="px-5 py-3">{frecuenciaTexto(p)}</td>
|
||||
<td className="px-5 py-3">
|
||||
{p.proximaFecha
|
||||
? formatFechaCorta(new Date(p.proximaFecha))
|
||||
: "—"}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-center">
|
||||
<EstadoProgramaBadge activo={p.activo} />
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<div className="flex items-center justify-center gap-3">
|
||||
<button
|
||||
onClick={() => abrirEditar(p)}
|
||||
className="text-xs text-primary hover:underline flex items-center gap-1"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
Editar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onToggleActivo(p)}
|
||||
className={`text-xs hover:underline flex items-center gap-1 ${
|
||||
p.activo ? "text-danger" : "text-success"
|
||||
}`}
|
||||
>
|
||||
<Power className="w-3 h-3" />
|
||||
{p.activo ? "Desactivar" : "Activar"}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dialogo && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
||||
onClick={() => setDialogo(null)}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-md rounded-xl bg-card-bg border border-border shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="px-5 py-4 border-b border-border font-semibold">
|
||||
{dialogo === "nuevo" ? "Nuevo programa" : "Editar programa"}
|
||||
</div>
|
||||
<div className="p-5 space-y-3">
|
||||
{dialogo === "nuevo" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Cliente</label>
|
||||
<select
|
||||
value={clienteId}
|
||||
onChange={(e) => setClienteId(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
{clientes.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.nombre}
|
||||
{c.empresa ? ` — ${c.empresa}` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-muted mt-1">
|
||||
¿No aparece?{" "}
|
||||
<Link to="/clientes?nuevo=1" className="text-primary hover:underline">
|
||||
Da de alta al cliente
|
||||
</Link>{" "}
|
||||
sin hacerle una cotización.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Concepto</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.concepto}
|
||||
onChange={(e) => set("concepto", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
placeholder="Ej. Gestion de publicidad"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Monto</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={form.monto}
|
||||
onChange={(e) => set("monto", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Frecuencia</label>
|
||||
<select
|
||||
value={form.frecuencia}
|
||||
onChange={(e) => set("frecuencia", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
<option value="semanal">Semanal</option>
|
||||
<option value="quincenal">Quincenal</option>
|
||||
<option value="mensual">Mensual</option>
|
||||
</select>
|
||||
</div>
|
||||
{form.frecuencia === "semanal" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Dia de la semana</label>
|
||||
<select
|
||||
value={form.diaSemana}
|
||||
onChange={(e) => set("diaSemana", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm bg-card-bg"
|
||||
>
|
||||
{DIAS.map((d, i) => (
|
||||
<option key={i} value={String(i)}>
|
||||
{d}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{form.frecuencia === "mensual" && (
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Dia del mes</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="31"
|
||||
value={form.diaMes}
|
||||
onChange={(e) => set("diaMes", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Fecha de inicio</label>
|
||||
<input
|
||||
type="date"
|
||||
value={form.fechaInicio}
|
||||
onChange={(e) => set("fechaInicio", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
<p className="text-xs text-muted mt-1">
|
||||
Si es una fecha pasada, se generan como pendientes todos los cobros desde ese día.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">
|
||||
Fecha de fin (opcional)
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
value={form.fechaFin}
|
||||
onChange={(e) => set("fechaFin", e.target.value)}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-5 py-4 border-t border-border flex justify-end gap-2">
|
||||
<button
|
||||
onClick={() => setDialogo(null)}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={guardar}
|
||||
disabled={guardando}
|
||||
className="px-4 py-2 rounded-lg text-sm text-white bg-primary hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{guardando ? "Guardando..." : "Guardar"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
Modal,
|
||||
claseBotonPrimario,
|
||||
claseBotonSecundario,
|
||||
claseCampo,
|
||||
claseEtiqueta,
|
||||
} from "@/components/ui/Modal";
|
||||
import { formatFechaCorta, formatMonto, hoyCalendario } from "@/lib/cobros-fechas";
|
||||
import type { PagoRow } from "./types";
|
||||
|
||||
export function RegistrarPagoDialog({
|
||||
pago,
|
||||
onClose,
|
||||
onRegistrado,
|
||||
}: {
|
||||
pago: PagoRow;
|
||||
onClose: () => void;
|
||||
onRegistrado: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const hoy = hoyCalendario().toISOString().slice(0, 10);
|
||||
const [fecha, setFecha] = useState(hoy);
|
||||
const [nota, setNota] = useState("");
|
||||
const [guardando, setGuardando] = useState(false);
|
||||
|
||||
const guardar = async () => {
|
||||
if (!fecha) {
|
||||
toast("Indica la fecha del pago", "error");
|
||||
return;
|
||||
}
|
||||
setGuardando(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cobros/pagos/${pago.id}/registrar`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ fecha, nota: nota.trim() || undefined }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
toast(data.error || "Error al registrar el pago", "error");
|
||||
return;
|
||||
}
|
||||
toast("Pago registrado", "success");
|
||||
onRegistrado();
|
||||
} catch {
|
||||
toast("Error de conexión", "error");
|
||||
} finally {
|
||||
setGuardando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
titulo="Registrar pago"
|
||||
descripcion={
|
||||
<>
|
||||
{pago.programa.cliente.nombre} · cobro del {formatFechaCorta(new Date(pago.fecha))} por{" "}
|
||||
<span className="font-medium text-foreground tabular-nums">
|
||||
{formatMonto(pago.monto, pago.programa.moneda)}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
onClose={onClose}
|
||||
onSubmit={guardar}
|
||||
acciones={
|
||||
<>
|
||||
<button type="button" onClick={onClose} className={claseBotonSecundario}>
|
||||
Cancelar
|
||||
</button>
|
||||
<button type="submit" disabled={guardando} className={claseBotonPrimario}>
|
||||
{guardando ? "Guardando..." : "Registrar pago"}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<label htmlFor="registrar-fecha" className={claseEtiqueta}>
|
||||
Fecha en que pagó
|
||||
</label>
|
||||
<input
|
||||
id="registrar-fecha"
|
||||
type="date"
|
||||
value={fecha}
|
||||
max={hoy}
|
||||
required
|
||||
onChange={(e) => setFecha(e.target.value)}
|
||||
className={claseCampo}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="registrar-nota" className={claseEtiqueta}>
|
||||
Nota interna (opcional)
|
||||
</label>
|
||||
<input
|
||||
id="registrar-nota"
|
||||
type="text"
|
||||
value={nota}
|
||||
maxLength={500}
|
||||
onChange={(e) => setNota(e.target.value)}
|
||||
placeholder="Ej. transferencia, efectivo, pagó en dos partes..."
|
||||
className={claseCampo}
|
||||
/>
|
||||
<p className="text-xs text-muted mt-1">Solo la ves tú; el cliente no la ve.</p>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export type ClienteOpt = {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
};
|
||||
|
||||
export type ProgramaRow = {
|
||||
id: string;
|
||||
concepto: string;
|
||||
monto: number;
|
||||
moneda: string;
|
||||
frecuencia: string;
|
||||
diaSemana: number | null;
|
||||
diaMes: number | null;
|
||||
activo: boolean;
|
||||
fechaInicio: string;
|
||||
fechaFin: string | null;
|
||||
cliente: ClienteOpt;
|
||||
pagosCount: number;
|
||||
proximaFecha: string | null;
|
||||
};
|
||||
|
||||
export type ComprobanteMeta = {
|
||||
id: string;
|
||||
archivoNombre: string;
|
||||
mime: string;
|
||||
tamano: number;
|
||||
subidoAt: string;
|
||||
};
|
||||
|
||||
export type PagoRow = {
|
||||
id: string;
|
||||
fecha: string;
|
||||
monto: number;
|
||||
estado: string;
|
||||
rechazoMotivo: string | null;
|
||||
verificadoAt: string | null;
|
||||
nota: string | null;
|
||||
programa: {
|
||||
concepto: string;
|
||||
moneda: string;
|
||||
cliente: { id: string; nombre: string; empresa: string | null };
|
||||
};
|
||||
comprobante: ComprobanteMeta | null;
|
||||
};
|
||||
|
||||
export type SaldoClienteRow = {
|
||||
clienteId: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
pagos: number;
|
||||
totales: Record<string, number>;
|
||||
masAntigua: string;
|
||||
diasAtraso: number;
|
||||
ultimoRecordatorio: string | null;
|
||||
contactable: boolean;
|
||||
};
|
||||
|
||||
export type ResultadoRecordatorioRow = {
|
||||
clienteId: string;
|
||||
cliente: string;
|
||||
pagos: number;
|
||||
totales: Record<string, number>;
|
||||
correo: "enviado" | "omitido" | "sin_email" | "error";
|
||||
push: number;
|
||||
entregado: boolean;
|
||||
pagoIds: string[];
|
||||
};
|
||||
@@ -0,0 +1,349 @@
|
||||
import { useState } from "react";
|
||||
import {
|
||||
CheckCircle2,
|
||||
Send,
|
||||
Mail,
|
||||
MessageSquare,
|
||||
Check,
|
||||
XCircle,
|
||||
Clock,
|
||||
RotateCcw,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
interface Props {
|
||||
cotizacionId: string;
|
||||
numero: string;
|
||||
estado: string;
|
||||
esAdmin: boolean;
|
||||
clienteEmail: string | null;
|
||||
clienteTelefono: string | null;
|
||||
onRefresh: () => void;
|
||||
}
|
||||
|
||||
export function CambiarEstadoButtons({
|
||||
cotizacionId,
|
||||
numero,
|
||||
estado,
|
||||
esAdmin,
|
||||
clienteEmail,
|
||||
clienteTelefono,
|
||||
onRefresh,
|
||||
}: Props) {
|
||||
const confirm = useConfirm();
|
||||
const showToast = useToast();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showEnviarModal, setShowEnviarModal] = useState(false);
|
||||
const [canal, setCanal] = useState<"email" | "whatsapp_chatwoot" | "manual">(
|
||||
clienteTelefono ? "whatsapp_chatwoot" : clienteEmail ? "email" : "manual"
|
||||
);
|
||||
const [destino, setDestino] = useState(clienteTelefono || clienteEmail || "");
|
||||
const [mensaje, setMensaje] = useState("");
|
||||
const [fallbackEmail, setFallbackEmail] = useState(true);
|
||||
|
||||
const handleAprobar = async () => {
|
||||
const ok = await confirm({
|
||||
title: "Aprobar cotización",
|
||||
message: `¿Confirmas aprobar la cotización ${numero}? Una vez aprobada podrá enviarse al cliente por correo o WhatsApp.`,
|
||||
confirmText: "Aprobar cotización",
|
||||
cancelText: "Cancelar",
|
||||
});
|
||||
if (!ok) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/aprobar`, {
|
||||
method: "POST",
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok) {
|
||||
showToast("Cotización aprobada correctamente", "success");
|
||||
onRefresh();
|
||||
} else {
|
||||
showToast(data.error || "No se pudo aprobar la cotización", "error");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEnviar = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/enviar`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
canal,
|
||||
destino: destino.trim() || undefined,
|
||||
mensaje: mensaje.trim() || undefined,
|
||||
fallbackEmail: canal === "whatsapp_chatwoot" ? fallbackEmail : undefined,
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok) {
|
||||
showToast(`Cotización enviada (${data.enviadaCanal || canal})`, "success");
|
||||
setShowEnviarModal(false);
|
||||
onRefresh();
|
||||
} else {
|
||||
showToast(data.error || "Error al enviar la cotización", "error");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTransicion = async (
|
||||
nuevoEstado: "aceptada" | "rechazada" | "vencida" | "borrador",
|
||||
etiqueta: string,
|
||||
danger = false
|
||||
) => {
|
||||
const ok = await confirm({
|
||||
title: `Cambiar estado a ${etiqueta}`,
|
||||
message: `¿Confirmas marcar la cotización ${numero} como "${etiqueta}"?`,
|
||||
confirmText: `Marcar ${etiqueta}`,
|
||||
cancelText: "Cancelar",
|
||||
danger,
|
||||
});
|
||||
if (!ok) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/estado`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ estado: nuevoEstado }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.ok) {
|
||||
showToast(`Cotización marcada como ${etiqueta}`, "success");
|
||||
onRefresh();
|
||||
} else {
|
||||
showToast(data.error || "Error al cambiar estado", "error");
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const cambiarCanal = (nuevo: "email" | "whatsapp_chatwoot" | "manual") => {
|
||||
setCanal(nuevo);
|
||||
if (nuevo === "email") setDestino(clienteEmail || "");
|
||||
else if (nuevo === "whatsapp_chatwoot") setDestino(clienteTelefono || "");
|
||||
else setDestino(clienteEmail || clienteTelefono || "");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<EstadoBadge estado={estado} />
|
||||
|
||||
{estado === "borrador" && esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAprobar}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
{loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle2 className="w-3.5 h-3.5" />}
|
||||
Aprobar cotización
|
||||
</button>
|
||||
)}
|
||||
|
||||
{estado === "aprobada" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEnviarModal(true)}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1 rounded-lg bg-primary text-white text-xs font-semibold hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
<Send className="w-3.5 h-3.5" />
|
||||
Enviar cotización
|
||||
</button>
|
||||
{esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Reabrir
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{estado === "enviada" && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("aceptada", "Aceptada")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-green-300 text-green-700 hover:bg-green-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5" />
|
||||
Aceptada
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("rechazada", "Rechazada", true)}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-red-300 text-red-700 hover:bg-red-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<XCircle className="w-3.5 h-3.5" />
|
||||
Rechazada
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("vencida", "Vencida")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-amber-300 text-amber-800 hover:bg-amber-50 text-xs font-medium disabled:opacity-50"
|
||||
>
|
||||
<Clock className="w-3.5 h-3.5" />
|
||||
Vencida
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{(estado === "rechazada" || estado === "vencida") && esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleTransicion("borrador", "Borrador")}
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border border-border text-xs text-muted hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Reabrir borrador
|
||||
</button>
|
||||
)}
|
||||
|
||||
{showEnviarModal && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4"
|
||||
onClick={() => !loading && setShowEnviarModal(false)}
|
||||
>
|
||||
<form
|
||||
onSubmit={handleEnviar}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-white rounded-xl border border-border shadow-xl max-w-md w-full p-5 space-y-4"
|
||||
>
|
||||
<div>
|
||||
<h3 className="font-semibold text-base">Enviar cotización {numero}</h3>
|
||||
<p className="text-xs text-muted mt-0.5">
|
||||
El PDF oficial se genera automáticamente al confirmar el envío.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("email")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "email"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<Mail className="w-4 h-4" />
|
||||
Correo
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("whatsapp_chatwoot")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "whatsapp_chatwoot"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4" />
|
||||
WhatsApp
|
||||
</button>
|
||||
{esAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cambiarCanal("manual")}
|
||||
className={`flex flex-col items-center gap-1 p-2.5 rounded-lg border text-xs font-medium ${
|
||||
canal === "manual"
|
||||
? "border-primary bg-primary-light/20 text-primary"
|
||||
: "border-border text-muted hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
Manual
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-muted mb-1">
|
||||
{canal === "email"
|
||||
? "Correo destino"
|
||||
: canal === "whatsapp_chatwoot"
|
||||
? "Teléfono WhatsApp"
|
||||
: "Destino / referencia"}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={destino}
|
||||
onChange={(e) => setDestino(e.target.value)}
|
||||
required={canal !== "manual"}
|
||||
placeholder={canal === "email" ? "[email protected]" : "4421234567"}
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{canal !== "manual" && (
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-muted mb-1">
|
||||
Mensaje adicional (opcional)
|
||||
</label>
|
||||
<textarea
|
||||
rows={3}
|
||||
value={mensaje}
|
||||
onChange={(e) => setMensaje(e.target.value)}
|
||||
placeholder="Nota breve para acompañar la propuesta..."
|
||||
className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canal === "whatsapp_chatwoot" && clienteEmail && (
|
||||
<label className="flex items-center gap-2 text-xs text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={fallbackEmail}
|
||||
onChange={(e) => setFallbackEmail(e.target.checked)}
|
||||
/>
|
||||
Si WhatsApp está fuera de la ventana de 24h, enviar por correo ({clienteEmail})
|
||||
</label>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-border">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowEnviarModal(false)}
|
||||
disabled={loading}
|
||||
className="px-3 py-2 rounded-lg border border-border text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-dark disabled:opacity-50"
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
Confirmar envío
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { ArrowLeft, Pencil } from "lucide-react";
|
||||
import {
|
||||
formatDate,
|
||||
formatCurrency,
|
||||
calcularTotalesOpcion,
|
||||
esCotizacionPorTiempo,
|
||||
tarifaHoraSugerida,
|
||||
IVA_RATE,
|
||||
type MetaOpcion,
|
||||
} from "@/lib/calculators";
|
||||
import { parseBrandingFromConfig, type BrandingConfig } from "@/lib/api";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { ExportExcelButtonSaved, ExportPDFButtonSaved, PreviewPDFButtonSaved } from "@/components/ExportButtons";
|
||||
import PropuestaIAPanel from "@/components/PropuestaIAPanel";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { DeleteCotizacionButton } from "./DeleteButton";
|
||||
import { CambiarEstadoButtons } from "./CambiarEstadoButtons";
|
||||
import { PreciosEditables } from "./PreciosEditables";
|
||||
import { RegistroHorasPanel, type RegistroHoraItem } from "./RegistroHorasPanel";
|
||||
|
||||
interface CotizacionServicioDetail {
|
||||
id: string;
|
||||
servicioCatalogoId: string | null;
|
||||
nombre: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
seleccionado: boolean;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: string[];
|
||||
esPersonalizado: boolean;
|
||||
horas: number | null;
|
||||
tarifaHora: number | null;
|
||||
modeloCobro: string | null;
|
||||
montoMinimo: number | null;
|
||||
horasIncluidas: number | null;
|
||||
opcion: string | null;
|
||||
servicioCatalogo?: { nombre: string } | null;
|
||||
}
|
||||
|
||||
interface CotizacionDetail {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
fecha: string;
|
||||
vigencia: string;
|
||||
estado: string;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
esquemaPago: string;
|
||||
incluirIva: boolean;
|
||||
esDoble: boolean;
|
||||
opcionesMetadata: { "1"?: MetaOpcion; "2"?: MetaOpcion } | null;
|
||||
observaciones: string | null;
|
||||
observacionesInternas: string | null;
|
||||
creadaPorAgente?: string | null;
|
||||
aprobadaAt?: string | null;
|
||||
aprobacionMetodo?: string | null;
|
||||
enviadaAt?: string | null;
|
||||
enviadaCanal?: string | null;
|
||||
enviadaDestino?: string | null;
|
||||
cliente: {
|
||||
id: string;
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
};
|
||||
asesor: { id: string; name: string; email?: string };
|
||||
servicios: CotizacionServicioDetail[];
|
||||
registrosHoras?: RegistroHoraItem[];
|
||||
}
|
||||
|
||||
export function CotizacionDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const { user } = useAuth();
|
||||
const esAdmin = user?.role === "admin";
|
||||
|
||||
const [cot, setCot] = useState<CotizacionDetail | null>(null);
|
||||
const [registrosHoras, setRegistrosHoras] = useState<RegistroHoraItem[]>([]);
|
||||
const [branding, setBranding] = useState<BrandingConfig>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${id}`, { credentials: "include" });
|
||||
if (res.status === 404) {
|
||||
setError("Cotización no encontrada");
|
||||
setCot(null);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error("No se pudo cargar la cotización");
|
||||
const data: CotizacionDetail = await res.json();
|
||||
setCot(data);
|
||||
|
||||
const requiereHoras =
|
||||
["aprobada", "enviada", "aceptada"].includes(data.estado) &&
|
||||
esCotizacionPorTiempo(data.servicios);
|
||||
|
||||
if (requiereHoras) {
|
||||
const [horasRes, cfgRes] = await Promise.all([
|
||||
Array.isArray(data.registrosHoras)
|
||||
? Promise.resolve(null)
|
||||
: fetch(`/api/cotizaciones/${id}/horas`, { credentials: "include" }),
|
||||
fetch("/api/configuracion", { credentials: "include" }),
|
||||
]);
|
||||
|
||||
if (Array.isArray(data.registrosHoras)) {
|
||||
setRegistrosHoras(data.registrosHoras);
|
||||
} else if (horasRes?.ok) {
|
||||
const h = await horasRes.json();
|
||||
setRegistrosHoras(Array.isArray(h) ? h : []);
|
||||
}
|
||||
if (cfgRes.ok) {
|
||||
const cfg = await cfgRes.json();
|
||||
setBranding(parseBrandingFromConfig(cfg));
|
||||
}
|
||||
} else {
|
||||
setRegistrosHoras(Array.isArray(data.registrosHoras) ? data.registrosHoras : []);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !cot) return <LoadingScreen />;
|
||||
if (error || !cot) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Link
|
||||
to="/cotizaciones"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Volver a cotizaciones
|
||||
</Link>
|
||||
<PageError message={error || "Cotización no encontrada"} onRetry={load} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const mostrarHoras =
|
||||
["aprobada", "enviada", "aceptada"].includes(cot.estado) &&
|
||||
esCotizacionPorTiempo(cot.servicios);
|
||||
|
||||
const serviciosUnicos = cot.servicios
|
||||
.filter((s) => s.tipoPago === "unico" && s.seleccionado)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||
precio: s.precio,
|
||||
modeloCobro: s.modeloCobro,
|
||||
tarifaHora: s.tarifaHora,
|
||||
}));
|
||||
|
||||
const serviciosMensuales = cot.servicios
|
||||
.filter((s) => s.tipoPago === "mensual" && s.seleccionado)
|
||||
.map((s) => ({
|
||||
id: s.id,
|
||||
nombre: s.servicioCatalogo?.nombre || s.nombre || "Servicio",
|
||||
precio: s.precio,
|
||||
modeloCobro: s.modeloCobro,
|
||||
tarifaHora: s.tarifaHora,
|
||||
}));
|
||||
|
||||
const opcionesMeta = cot.opcionesMetadata ?? {};
|
||||
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 flex-wrap gap-3">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link
|
||||
to="/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 flex-wrap">
|
||||
<PreviewPDFButtonSaved cotizacionId={cot.id} />
|
||||
<ExportPDFButtonSaved cotizacionId={cot.id} />
|
||||
<ExportExcelButtonSaved cotizacionId={cot.id} />
|
||||
<Link
|
||||
to={`/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">Información de la Cotización</h2>
|
||||
{(cot.creadaPorAgente || cot.aprobadaAt || cot.enviadaAt) && (
|
||||
<div className="flex flex-wrap gap-2 mb-4 text-xs">
|
||||
{cot.creadaPorAgente && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-purple-100 text-purple-800 font-medium">
|
||||
Creada por agente: {cot.creadaPorAgente}
|
||||
</span>
|
||||
)}
|
||||
{cot.aprobadaAt && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-indigo-50 text-indigo-800 border border-indigo-200">
|
||||
Aprobada el {formatDate(new Date(cot.aprobadaAt))}
|
||||
{cot.aprobacionMetodo ? ` (${cot.aprobacionMetodo === "enlace_firmado" ? "enlace firmado" : "panel admin"})` : ""}
|
||||
</span>
|
||||
)}
|
||||
{cot.enviadaAt && (
|
||||
<span className="px-2.5 py-1 rounded-full bg-blue-50 text-blue-800 border border-blue-200">
|
||||
Enviada el {formatDate(new Date(cot.enviadaAt))}
|
||||
{cot.enviadaCanal ? ` vía ${cot.enviadaCanal}` : ""}
|
||||
{cot.enviadaDestino ? ` a ${cot.enviadaDestino}` : ""}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<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(new Date(cot.fecha))}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Vigencia</span>
|
||||
<p className="font-medium">{formatDate(new Date(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}
|
||||
numero={cot.numero}
|
||||
estado={cot.estado}
|
||||
esAdmin={esAdmin}
|
||||
clienteEmail={cot.cliente.email}
|
||||
clienteTelefono={cot.cliente.telefono}
|
||||
onRefresh={load}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</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}
|
||||
serviciosMensuales={serviciosMensuales}
|
||||
/>
|
||||
|
||||
{mostrarHoras && (
|
||||
<RegistroHorasPanel
|
||||
cotizacionId={cot.id}
|
||||
numero={cot.numero}
|
||||
clienteNombre={cot.cliente.nombre}
|
||||
clienteEmpresa={cot.cliente.empresa}
|
||||
proyecto={cot.proyecto}
|
||||
tarifaSugerida={tarifaHoraSugerida(cot.servicios)}
|
||||
incluirIva={cot.incluirIva}
|
||||
branding={branding}
|
||||
registrosIniciales={registrosHoras}
|
||||
/>
|
||||
)}
|
||||
|
||||
{cot.observaciones && (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h3 className="font-semibold mb-2 flex items-center gap-2">
|
||||
Observaciones
|
||||
<span className="text-[11px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full bg-primary-light text-primary">
|
||||
Las ve el cliente
|
||||
</span>
|
||||
</h3>
|
||||
<p className="text-sm text-muted whitespace-pre-wrap">{cot.observaciones}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PropuestaIAPanel cotizacionId={cot.id} numero={cot.numero} />
|
||||
|
||||
{cot.observacionesInternas && (
|
||||
<div className="rounded-xl border border-amber-300 bg-amber-50 p-5 mt-6">
|
||||
<h3 className="font-semibold mb-2 flex items-center gap-2 text-amber-900">
|
||||
Notas internas
|
||||
<span className="text-[11px] font-semibold uppercase tracking-wide px-2 py-0.5 rounded-full bg-amber-200 text-amber-900">
|
||||
No sale de la app
|
||||
</span>
|
||||
</h3>
|
||||
<p className="text-sm text-amber-900/80 whitespace-pre-wrap">{cot.observacionesInternas}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Pencil, Search } from "lucide-react";
|
||||
import { formatDate, formatCurrency } from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
import { ListDeleteButton } from "./ListDeleteButton";
|
||||
|
||||
export interface CotizacionRow {
|
||||
id: string;
|
||||
numero: string;
|
||||
estado: string;
|
||||
fecha: string;
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
asesor: { name: string };
|
||||
servicios: { tipoPago: string; seleccionado: boolean; precio: number }[];
|
||||
}
|
||||
|
||||
export function CotizacionesList({
|
||||
cotizaciones,
|
||||
onRefresh,
|
||||
}: {
|
||||
cotizaciones: CotizacionRow[];
|
||||
onRefresh: () => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (!search) return cotizaciones;
|
||||
const q = search.toLowerCase();
|
||||
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 (
|
||||
<>
|
||||
<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
|
||||
to={`/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(new Date(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
|
||||
to={`/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} onDeleted={onRefresh} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Plus, FileText } from "lucide-react";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { CotizacionesList, type CotizacionRow } from "./CotizacionesList";
|
||||
|
||||
export function CotizacionesPage() {
|
||||
const [cotizaciones, setCotizaciones] = useState<CotizacionRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/cotizaciones", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudieron cargar las cotizaciones");
|
||||
setCotizaciones(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !cotizaciones) return <LoadingScreen />;
|
||||
if (error || !cotizaciones) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
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
|
||||
to="/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
|
||||
to="/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} onRefresh={load} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useState } from "react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
export function DeleteCotizacionButton({
|
||||
cotizacionId,
|
||||
cotizacionNumero,
|
||||
}: {
|
||||
cotizacionId: string;
|
||||
cotizacionNumero: string;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const showToast = useToast();
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (res.ok) {
|
||||
navigate("/cotizaciones");
|
||||
} else {
|
||||
showToast("Error al eliminar", "error");
|
||||
setConfirming(false);
|
||||
}
|
||||
} catch {
|
||||
showToast("Error al eliminar", "error");
|
||||
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,180 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import {
|
||||
CotizacionForm,
|
||||
type Asesor,
|
||||
type ExistingData,
|
||||
type ServicioCatalogo,
|
||||
} from "@/components/CotizacionForm";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
|
||||
interface EditCotizacionResponse {
|
||||
id: string;
|
||||
numero: string;
|
||||
asesorId: string;
|
||||
fecha: string;
|
||||
vigencia: string;
|
||||
moneda: string;
|
||||
tipoCambio: string;
|
||||
proyecto: string;
|
||||
esquemaPago: string;
|
||||
incluirBonos: boolean;
|
||||
incluirFinanciamiento: boolean;
|
||||
observaciones: string | null;
|
||||
observacionesInternas: string | null;
|
||||
esDoble: boolean;
|
||||
opcionesMetadata: { "1"?: object; "2"?: object } | null;
|
||||
estado: string;
|
||||
cliente: {
|
||||
nombre: string;
|
||||
empresa: string | null;
|
||||
email: string | null;
|
||||
telefono: string | null;
|
||||
};
|
||||
asesor: { id: string; name: string };
|
||||
planBucefalo: { nivel: string } | null;
|
||||
servicios: {
|
||||
id: string;
|
||||
servicioCatalogoId: string | null;
|
||||
nombre: string | null;
|
||||
fase: number;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
tiempoEntrega: string;
|
||||
entregables: unknown;
|
||||
esPersonalizado: boolean;
|
||||
horas: number | null;
|
||||
tarifaHora: number | null;
|
||||
modeloCobro: string | null;
|
||||
montoMinimo: number | null;
|
||||
horasIncluidas: number | null;
|
||||
opcion: string | null;
|
||||
servicioCatalogo?: { nombre: string } | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
export function EditarCotizacionPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [data, setData] = useState<{
|
||||
existingData: ExistingData;
|
||||
servicios: ServicioCatalogo[];
|
||||
asesores: Asesor[];
|
||||
} | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [cRes, sRes, aRes] = await Promise.all([
|
||||
fetch(`/api/cotizaciones/${id}`, { credentials: "include" }),
|
||||
fetch("/api/catalogo?activo=true", { credentials: "include" }),
|
||||
fetch("/api/asesores", { credentials: "include" }),
|
||||
]);
|
||||
if (cRes.status === 404) {
|
||||
setError("Cotización no encontrada");
|
||||
setData(null);
|
||||
return;
|
||||
}
|
||||
if (!cRes.ok || !sRes.ok || !aRes.ok) {
|
||||
throw new Error("No se pudo cargar la cotización para editar");
|
||||
}
|
||||
const [cot, serviciosRaw, asesoresResp]: [
|
||||
EditCotizacionResponse,
|
||||
ServicioCatalogo[],
|
||||
{ asesores: Asesor[] },
|
||||
] = await Promise.all([cRes.json(), sRes.json(), aRes.json()]);
|
||||
|
||||
const existingData: 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: new Date(cot.fecha),
|
||||
vigencia: new Date(cot.vigencia),
|
||||
moneda: cot.moneda,
|
||||
tipoCambio: cot.tipoCambio,
|
||||
proyecto: cot.proyecto,
|
||||
esquemaPago: cot.esquemaPago,
|
||||
incluirBonos: cot.incluirBonos,
|
||||
incluirFinanciamiento: cot.incluirFinanciamiento,
|
||||
observaciones: cot.observaciones || "",
|
||||
observacionesInternas: cot.observacionesInternas || "",
|
||||
planBucefaloNivel: cot.planBucefalo?.nivel || null,
|
||||
esDoble: cot.esDoble,
|
||||
opciones: cot.opcionesMetadata ?? {},
|
||||
servicios: cot.servicios.map((s) => ({
|
||||
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,
|
||||
};
|
||||
|
||||
const servicios: ServicioCatalogo[] = (Array.isArray(serviciosRaw) ? serviciosRaw : []).map(
|
||||
(s) => ({
|
||||
...s,
|
||||
entregablesDefault: Array.isArray(s.entregablesDefault) ? s.entregablesDefault : [],
|
||||
categoriaNombre: s.categoriaNombre || "Sin categoria",
|
||||
})
|
||||
);
|
||||
|
||||
setData({
|
||||
existingData,
|
||||
servicios,
|
||||
asesores: Array.isArray(asesoresResp.asesores) ? asesoresResp.asesores : [],
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Link
|
||||
to="/cotizaciones"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Volver a cotizaciones
|
||||
</Link>
|
||||
<PageError message={error || "Cotización no encontrada"} onRetry={load} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CotizacionForm
|
||||
mode="edit"
|
||||
existingData={data.existingData}
|
||||
servicios={data.servicios}
|
||||
asesores={data.asesores}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useState } from "react";
|
||||
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
export function ListDeleteButton({
|
||||
id,
|
||||
onDeleted,
|
||||
}: {
|
||||
id: string;
|
||||
onDeleted: () => void;
|
||||
}) {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const showConfirm = useConfirm();
|
||||
const showToast = useToast();
|
||||
|
||||
const handleDelete = async () => {
|
||||
const ok = await showConfirm({
|
||||
title: "Eliminar cotización",
|
||||
message: "¿Eliminar esta cotización?",
|
||||
confirmText: "Eliminar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
setDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${id}`, { method: "DELETE" });
|
||||
if (res.ok) onDeleted();
|
||||
else showToast("Error al eliminar", "error");
|
||||
} catch {
|
||||
showToast("Error al eliminar", "error");
|
||||
} 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,75 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
CotizacionForm,
|
||||
type Asesor,
|
||||
type ServicioCatalogo,
|
||||
} from "@/components/CotizacionForm";
|
||||
import { normalizarPaquetes, type PaqueteNormalizado } from "@/lib/api";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
|
||||
interface NuevaData {
|
||||
servicios: ServicioCatalogo[];
|
||||
asesores: Asesor[];
|
||||
paquetes: PaqueteNormalizado[];
|
||||
nextSeq: number;
|
||||
}
|
||||
|
||||
export function NuevaCotizacionPage() {
|
||||
const [data, setData] = useState<NuevaData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [sRes, aRes, pRes] = await Promise.all([
|
||||
fetch("/api/catalogo?activo=true", { credentials: "include" }),
|
||||
fetch("/api/asesores", { credentials: "include" }),
|
||||
fetch("/api/paquetes", { credentials: "include" }),
|
||||
]);
|
||||
if (!sRes.ok || !aRes.ok || !pRes.ok) {
|
||||
throw new Error("No se pudieron cargar los datos para cotizar");
|
||||
}
|
||||
const [serviciosRaw, asesoresResp, paquetesRaw] = await Promise.all([
|
||||
sRes.json(),
|
||||
aRes.json(),
|
||||
pRes.json(),
|
||||
]);
|
||||
const servicios: ServicioCatalogo[] = (Array.isArray(serviciosRaw) ? serviciosRaw : []).map(
|
||||
(s: ServicioCatalogo) => ({
|
||||
...s,
|
||||
entregablesDefault: Array.isArray(s.entregablesDefault) ? s.entregablesDefault : [],
|
||||
categoriaNombre: s.categoriaNombre || "Sin categoria",
|
||||
})
|
||||
);
|
||||
setData({
|
||||
servicios,
|
||||
asesores: Array.isArray(asesoresResp.asesores) ? asesoresResp.asesores : [],
|
||||
paquetes: normalizarPaquetes(paquetesRaw),
|
||||
nextSeq: typeof asesoresResp.nextSeq === "number" ? asesoresResp.nextSeq : 1,
|
||||
});
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return (
|
||||
<CotizacionForm
|
||||
mode="new"
|
||||
servicios={data.servicios}
|
||||
asesores={data.asesores}
|
||||
paquetes={data.paquetes}
|
||||
nextSeq={data.nextSeq}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { formatCurrency, precioDisplay, IVA_RATE } from "@/lib/calculators";
|
||||
|
||||
interface ServicioItem {
|
||||
id: string;
|
||||
nombre: string;
|
||||
precio: number;
|
||||
modeloCobro?: string | null;
|
||||
tarifaHora?: number | null;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
useEffect(() => {
|
||||
setUnicos(serviciosUnicos);
|
||||
}, [serviciosUnicos]);
|
||||
|
||||
useEffect(() => {
|
||||
setMensuales(serviciosMensuales);
|
||||
}, [serviciosMensuales]);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
const renderFila = (s: ServicioItem, tipo: "unico" | "mensual") => (
|
||||
<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">
|
||||
{s.modeloCobro === "demanda" ? (
|
||||
<span className="text-muted">{precioDisplay(s)}</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-muted text-xs">$</span>
|
||||
<input
|
||||
type="number"
|
||||
value={s.precio}
|
||||
onChange={(e) =>
|
||||
handlePrecioChange(s.id, parseFloat(e.target.value) || 0, tipo)
|
||||
}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
{saving === s.id && <span className="text-xs text-muted">...</span>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
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) => renderFila(s, "unico"))}
|
||||
</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) => renderFila(s, "mensual"))}
|
||||
</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,820 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Clock, Plus, Trash2, Pencil, Download, Eye, X, CheckCircle2, CircleDashed, RotateCcw } from "lucide-react";
|
||||
import { useConfirm, useToast } from "@/components/ui/DialogProvider";
|
||||
import {
|
||||
formatCurrency,
|
||||
formatFechaRegistro,
|
||||
periodoAgrupacion,
|
||||
calcularHorasRango,
|
||||
resumenPagoHoras,
|
||||
esPagada,
|
||||
MODOS_AGRUPACION,
|
||||
IVA_RATE,
|
||||
type ModoAgrupacion,
|
||||
} from "@/lib/calculators";
|
||||
|
||||
export interface RegistroHoraItem {
|
||||
id: string;
|
||||
fecha: string;
|
||||
horaInicio: string;
|
||||
horaFin: string;
|
||||
horas: number;
|
||||
tarifaHora: number;
|
||||
descripcion: string;
|
||||
estadoPago: string;
|
||||
fechaPago?: string | null;
|
||||
}
|
||||
|
||||
interface Branding {
|
||||
colorPrimario?: string;
|
||||
colorSecundario?: string;
|
||||
logoBase64?: string;
|
||||
logoMime?: string;
|
||||
}
|
||||
|
||||
interface RegistroHorasPanelProps {
|
||||
cotizacionId: string;
|
||||
numero: string;
|
||||
clienteNombre: string;
|
||||
clienteEmpresa: string | null;
|
||||
proyecto: string;
|
||||
tarifaSugerida: number;
|
||||
incluirIva: boolean;
|
||||
branding: Branding;
|
||||
registrosIniciales: RegistroHoraItem[];
|
||||
}
|
||||
|
||||
type FiltroEstado = "todas" | "por_pagar" | "pagada";
|
||||
|
||||
const FILTROS_ESTADO: { value: FiltroEstado; label: string }[] = [
|
||||
{ value: "por_pagar", label: "Por pagar" },
|
||||
{ value: "pagada", label: "Pagadas" },
|
||||
{ value: "todas", label: "Todas" },
|
||||
];
|
||||
|
||||
const TITULO_NOTA: Record<FiltroEstado, string> = {
|
||||
por_pagar: "Nota de horas por pagar",
|
||||
pagada: "Recibo de horas pagadas",
|
||||
todas: "Estado de cuenta de horas",
|
||||
};
|
||||
|
||||
function hoyISO(): string {
|
||||
const d = new Date();
|
||||
const p2 = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`;
|
||||
}
|
||||
|
||||
const formVacio = (tarifa: number) => ({
|
||||
fecha: hoyISO(),
|
||||
horaInicio: "09:00",
|
||||
horaFin: "13:00",
|
||||
descripcion: "",
|
||||
tarifaHora: tarifa,
|
||||
});
|
||||
|
||||
const INPUT = "px-2 py-1.5 border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-primary";
|
||||
|
||||
export function RegistroHorasPanel({
|
||||
cotizacionId,
|
||||
numero,
|
||||
clienteNombre,
|
||||
clienteEmpresa,
|
||||
proyecto,
|
||||
tarifaSugerida,
|
||||
incluirIva,
|
||||
branding,
|
||||
registrosIniciales,
|
||||
}: RegistroHorasPanelProps) {
|
||||
const showConfirm = useConfirm();
|
||||
const showToast = useToast();
|
||||
const [registros, setRegistros] = useState<RegistroHoraItem[]>(registrosIniciales);
|
||||
const [form, setForm] = useState(formVacio(tarifaSugerida));
|
||||
const [editId, setEditId] = useState<string | null>(null);
|
||||
const [modo, setModo] = useState<ModoAgrupacion>("detalle");
|
||||
const [estadoFiltro, setEstadoFiltro] = useState<FiltroEstado>("por_pagar");
|
||||
const [from, setFrom] = useState("");
|
||||
const [to, setTo] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [descargando, setDescargando] = useState(false);
|
||||
const [togglingId, setTogglingId] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [previewHtml, setPreviewHtml] = useState<string | null>(null);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
|
||||
const horasPreview = calcularHorasRango(form.horaInicio, form.horaFin);
|
||||
|
||||
const porFecha = useMemo(() => {
|
||||
return registros
|
||||
.filter((r) => {
|
||||
const d = r.fecha.slice(0, 10);
|
||||
if (from && d < from) return false;
|
||||
if (to && d > to) return false;
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) =>
|
||||
a.fecha === b.fecha
|
||||
? a.horaInicio.localeCompare(b.horaInicio)
|
||||
: a.fecha.localeCompare(b.fecha)
|
||||
);
|
||||
}, [registros, from, to]);
|
||||
|
||||
const resumen = useMemo(() => resumenPagoHoras(porFecha), [porFecha]);
|
||||
|
||||
const filtrados = useMemo(() => {
|
||||
if (estadoFiltro === "todas") return porFecha;
|
||||
return porFecha.filter((r) =>
|
||||
estadoFiltro === "pagada" ? esPagada(r.estadoPago) : !esPagada(r.estadoPago)
|
||||
);
|
||||
}, [porFecha, estadoFiltro]);
|
||||
|
||||
const grupos = useMemo(() => {
|
||||
if (modo === "detalle") return [];
|
||||
const map = new Map<string, { etiqueta: string; horas: number; importe: number; count: number }>();
|
||||
for (const r of filtrados) {
|
||||
const { clave, etiqueta } = periodoAgrupacion(new Date(r.fecha), modo);
|
||||
const g = map.get(clave) ?? { etiqueta, horas: 0, importe: 0, count: 0 };
|
||||
g.horas += r.horas;
|
||||
g.importe += r.horas * r.tarifaHora;
|
||||
g.count += 1;
|
||||
map.set(clave, g);
|
||||
}
|
||||
return [...map.entries()]
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([clave, g]) => ({ clave, ...g }));
|
||||
}, [filtrados, modo]);
|
||||
|
||||
const ivaFactor = incluirIva ? 1 + IVA_RATE : 1;
|
||||
|
||||
const totalHoras = filtrados.reduce((a, r) => a + r.horas, 0);
|
||||
const subtotal = filtrados.reduce((a, r) => a + r.horas * r.tarifaHora, 0);
|
||||
const iva = incluirIva ? subtotal * IVA_RATE : 0;
|
||||
const total = subtotal + iva;
|
||||
|
||||
const resetForm = () => {
|
||||
setForm(formVacio(tarifaSugerida));
|
||||
setEditId(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (calcularHorasRango(form.horaInicio, form.horaFin) <= 0) {
|
||||
setError("El rango es invalido: la hora fin debe ser mayor a la de inicio.");
|
||||
return;
|
||||
}
|
||||
if (!form.descripcion.trim()) {
|
||||
setError("Agrega una descripcion breve de lo realizado.");
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const url = editId
|
||||
? `/api/cotizaciones/${cotizacionId}/horas/${editId}`
|
||||
: `/api/cotizaciones/${cotizacionId}/horas`;
|
||||
const res = await fetch(url, {
|
||||
method: editId ? "PUT" : "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
setError(data.error || "No se pudo guardar el registro");
|
||||
return;
|
||||
}
|
||||
setRegistros((prev) =>
|
||||
editId ? prev.map((r) => (r.id === editId ? data : r)) : [...prev, data]
|
||||
);
|
||||
resetForm();
|
||||
} catch {
|
||||
setError("Error de conexion al guardar");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (r: RegistroHoraItem) => {
|
||||
setEditId(r.id);
|
||||
setError(null);
|
||||
setForm({
|
||||
fecha: r.fecha.slice(0, 10),
|
||||
horaInicio: r.horaInicio,
|
||||
horaFin: r.horaFin,
|
||||
descripcion: r.descripcion,
|
||||
tarifaHora: r.tarifaHora,
|
||||
});
|
||||
window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Eliminar registro",
|
||||
message: "¿Eliminar este registro de horas?",
|
||||
confirmText: "Eliminar",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
const prev = registros;
|
||||
setRegistros((rs) => rs.filter((r) => r.id !== id));
|
||||
if (editId === id) resetForm();
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/horas/${id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!res.ok) setRegistros(prev);
|
||||
} catch {
|
||||
setRegistros(prev);
|
||||
}
|
||||
};
|
||||
|
||||
const cambiarEstado = async (r: RegistroHoraItem, nuevo: "por_pagar" | "pagada") => {
|
||||
if (esPagada(r.estadoPago) === (nuevo === "pagada")) return;
|
||||
const prev = registros;
|
||||
setTogglingId(r.id);
|
||||
setRegistros((rs) => rs.map((x) => (x.id === r.id ? { ...x, estadoPago: nuevo } : x)));
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/horas/${r.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ estadoPago: nuevo }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) setRegistros(prev);
|
||||
else setRegistros((rs) => rs.map((x) => (x.id === r.id ? data : x)));
|
||||
} catch {
|
||||
setRegistros(prev);
|
||||
} finally {
|
||||
setTogglingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const regresarPorPagar = async (r: RegistroHoraItem) => {
|
||||
const ok = await showConfirm({
|
||||
title: "Regresar a Por pagar",
|
||||
message: 'Se quitará la marca de pagada y esta partida volverá a contar como pendiente de cobro.',
|
||||
confirmText: "Regresar a Por pagar",
|
||||
});
|
||||
if (!ok) return;
|
||||
cambiarEstado(r, "por_pagar");
|
||||
};
|
||||
|
||||
const abrirPreview = () => setPreviewHtml(construirHTMLNota());
|
||||
|
||||
const descargarNotaPDF = async () => {
|
||||
setDescargando(true);
|
||||
try {
|
||||
const res = await fetch(`/api/cotizaciones/${cotizacionId}/nota-horas`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ estado: estadoFiltro, modo, from, to }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
showToast("No se pudo generar el PDF", "error");
|
||||
return;
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const fechas = filtrados.map((r) => r.fecha.slice(0, 10)).sort();
|
||||
const dd = (iso: string) => {
|
||||
const [y, mo, d] = iso.split("-");
|
||||
return `${d}-${mo}-${y}`;
|
||||
};
|
||||
const rango = fechas.length ? `${dd(fechas[0])}_${dd(fechas[fechas.length - 1])}` : "";
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${TITULO_NOTA[estadoFiltro]} ${numero}${rango ? ` - ${rango}` : ""}.pdf`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 2000);
|
||||
} catch {
|
||||
showToast("Error de conexión al generar el PDF", "error");
|
||||
} finally {
|
||||
setDescargando(false);
|
||||
}
|
||||
};
|
||||
|
||||
const badgeEstado = (estadoPago: string) => {
|
||||
const pagada = esPagada(estadoPago);
|
||||
return (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${
|
||||
pagada ? "bg-green-100 text-green-800" : "bg-amber-100 text-amber-800"
|
||||
}`}
|
||||
>
|
||||
{pagada ? <CheckCircle2 className="w-3 h-3" /> : <CircleDashed className="w-3 h-3" />}
|
||||
{pagada ? "Pagada" : "Por pagar"}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
const construirHTMLNota = () => {
|
||||
const PRIMARY = branding.colorPrimario || "#0400C4";
|
||||
const DARK = branding.colorSecundario || "#0F172A";
|
||||
const logoSrc = branding.logoBase64
|
||||
? `data:${branding.logoMime || "image/png"};base64,${branding.logoBase64}`
|
||||
: "";
|
||||
|
||||
const periodoTexto =
|
||||
from || to
|
||||
? `Periodo: ${from ? formatFechaRegistro(new Date(`${from}T12:00:00Z`)) : "inicio"} al ${
|
||||
to ? formatFechaRegistro(new Date(`${to}T12:00:00Z`)) : "hoy"
|
||||
}`
|
||||
: "Periodo: todos los registros";
|
||||
|
||||
const modoLabel = MODOS_AGRUPACION.find((m) => m.value === modo)?.label ?? "";
|
||||
const titulo = TITULO_NOTA[estadoFiltro];
|
||||
const mostrarColEstado = estadoFiltro === "todas" && modo === "detalle";
|
||||
|
||||
const cuerpo =
|
||||
modo === "detalle"
|
||||
? `<thead><tr>
|
||||
<th>Fecha</th><th>Horario</th><th class="r">Horas</th>
|
||||
<th class="r">Tarifa</th><th class="r">Importe</th><th>Descripcion</th>${
|
||||
mostrarColEstado ? "<th>Estado</th>" : ""
|
||||
}
|
||||
</tr></thead>
|
||||
<tbody>${filtrados
|
||||
.map(
|
||||
(r) => `<tr>
|
||||
<td>${formatFechaRegistro(new Date(r.fecha))}</td>
|
||||
<td>${r.horaInicio}–${r.horaFin}</td>
|
||||
<td class="r">${r.horas.toFixed(2)}</td>
|
||||
<td class="r">${formatCurrency(r.tarifaHora)}</td>
|
||||
<td class="r">${formatCurrency(r.horas * r.tarifaHora)}</td>
|
||||
<td>${escapeHtml(r.descripcion)}</td>${
|
||||
mostrarColEstado
|
||||
? `<td>${esPagada(r.estadoPago) ? "Pagada" : "Por pagar"}</td>`
|
||||
: ""
|
||||
}
|
||||
</tr>`
|
||||
)
|
||||
.join("")}</tbody>`
|
||||
: `<thead><tr>
|
||||
<th>${modoLabel}</th><th class="r">Registros</th>
|
||||
<th class="r">Horas</th><th class="r">Importe</th>
|
||||
</tr></thead>
|
||||
<tbody>${grupos
|
||||
.map(
|
||||
(g) => `<tr>
|
||||
<td>${escapeHtml(g.etiqueta)}</td>
|
||||
<td class="r">${g.count}</td>
|
||||
<td class="r">${g.horas.toFixed(2)}</td>
|
||||
<td class="r">${formatCurrency(g.importe)}</td>
|
||||
</tr>`
|
||||
)
|
||||
.join("")}</tbody>`;
|
||||
|
||||
const etiquetaTotal =
|
||||
estadoFiltro === "pagada" ? "Total pagado" : estadoFiltro === "todas" ? "Total" : "Total a pagar";
|
||||
|
||||
const totalesHTML = `
|
||||
<table class="tot">
|
||||
<tr><td>Total de horas</td><td class="r">${totalHoras.toFixed(2)} h</td></tr>
|
||||
<tr><td>Subtotal</td><td class="r">${formatCurrency(subtotal)}</td></tr>
|
||||
${incluirIva ? `<tr><td>IVA (16%)</td><td class="r">${formatCurrency(iva)}</td></tr>` : ""}
|
||||
<tr class="grand"><td>${etiquetaTotal}</td><td class="r">${formatCurrency(total)}</td></tr>
|
||||
</table>`;
|
||||
|
||||
return `<!doctype html><html lang="es"><head><meta charset="utf-8">
|
||||
<title>${escapeHtml(titulo)} ${escapeHtml(numero)}</title>
|
||||
<style>
|
||||
*{box-sizing:border-box} body{font-family:Arial,Helvetica,sans-serif;color:#1f2937;margin:40px;font-size:13px}
|
||||
h1{font-size:20px;margin:0 0 4px;color:${DARK}} .muted{color:#6b7280}
|
||||
.head{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:3px solid ${PRIMARY};padding-bottom:12px;margin-bottom:16px}
|
||||
.brand{display:flex;align-items:center;gap:14px}
|
||||
.logo{height:52px;width:auto;max-width:220px;object-fit:contain}
|
||||
.meta{margin:12px 0;line-height:1.6}
|
||||
table{width:100%;border-collapse:collapse;margin-top:8px}
|
||||
th,td{border:1px solid #d1d5db;padding:6px 8px;text-align:left;vertical-align:top}
|
||||
th{background:#f3f4f6;font-size:11px;text-transform:uppercase;letter-spacing:.03em}
|
||||
.r{text-align:right;white-space:nowrap}
|
||||
.tot{width:auto;min-width:280px;margin-left:auto;margin-top:16px}
|
||||
.tot td{border:none;padding:4px 8px}
|
||||
.tot .grand td{border-top:2px solid ${PRIMARY};font-weight:bold;font-size:15px;padding-top:8px;color:${DARK}}
|
||||
.foot{margin-top:32px;color:#6b7280;font-size:11px;text-align:center}
|
||||
@page{margin:0}
|
||||
@media print{body{margin:0;padding:14mm}}
|
||||
</style></head><body>
|
||||
<div class="head">
|
||||
<div class="brand">
|
||||
${logoSrc ? `<img src="${logoSrc}" alt="Logo" class="logo">` : ""}
|
||||
<div>
|
||||
<h1>${escapeHtml(titulo)}</h1>
|
||||
<div class="muted">Cotizacion ${escapeHtml(numero)} · ${escapeHtml(proyecto)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="muted" style="text-align:right">Emitida: ${formatFechaRegistro(new Date(new Date().toISOString().slice(0, 10) + "T12:00:00Z"))}</div>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div><b>Cliente:</b> ${escapeHtml(clienteEmpresa || clienteNombre)}</div>
|
||||
${clienteEmpresa ? `<div><b>Contacto:</b> ${escapeHtml(clienteNombre)}</div>` : ""}
|
||||
<div class="muted">${periodoTexto} · Desglose ${modoLabel.toLowerCase()}</div>
|
||||
</div>
|
||||
<table>${cuerpo}</table>
|
||||
${totalesHTML}
|
||||
<div class="foot">Documento generado desde el Cotizador. Conteo de horas trabajadas para cobro del proyecto.</div>
|
||||
</body></html>`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<div className="flex items-center justify-between mb-4 gap-3 flex-wrap">
|
||||
<h2 className="font-semibold text-lg flex items-center gap-2">
|
||||
<Clock className="w-5 h-5 text-primary" />
|
||||
Registro de horas
|
||||
</h2>
|
||||
<button
|
||||
onClick={abrirPreview}
|
||||
disabled={filtrados.length === 0}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-40"
|
||||
>
|
||||
<Eye className="w-4 h-4 text-blue-600" />
|
||||
{estadoFiltro === "pagada"
|
||||
? "Previsualizar recibo"
|
||||
: estadoFiltro === "todas"
|
||||
? "Previsualizar estado de cuenta"
|
||||
: "Previsualizar nota por pagar"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEstadoFiltro("por_pagar")}
|
||||
className={`text-left rounded-lg border p-3 transition ${
|
||||
estadoFiltro === "por_pagar"
|
||||
? "border-amber-400 bg-amber-50 ring-1 ring-amber-300"
|
||||
: "border-amber-200 bg-amber-50/60 hover:bg-amber-50"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 text-amber-800 text-sm font-medium">
|
||||
<CircleDashed className="w-4 h-4" /> Por pagar
|
||||
</div>
|
||||
<div className="mt-1 text-2xl font-bold text-amber-900">
|
||||
{formatCurrency(resumen.porPagar.importe * ivaFactor)}
|
||||
</div>
|
||||
<div className="text-xs text-amber-800/80">
|
||||
{resumen.porPagar.horas.toFixed(2)} h · {resumen.porPagar.count} registro(s)
|
||||
{incluirIva ? " · IVA incluido" : ""}
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEstadoFiltro("pagada")}
|
||||
className={`text-left rounded-lg border p-3 transition ${
|
||||
estadoFiltro === "pagada"
|
||||
? "border-green-400 bg-green-50 ring-1 ring-green-300"
|
||||
: "border-green-200 bg-green-50/60 hover:bg-green-50"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 text-green-800 text-sm font-medium">
|
||||
<span className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-4 h-4" /> Pagado
|
||||
</span>
|
||||
{resumen.pagada.count > 0 && (
|
||||
<span className="text-xs font-normal text-green-700/90 underline">Ver / editar</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 text-2xl font-bold text-green-900">
|
||||
{formatCurrency(resumen.pagada.importe * ivaFactor)}
|
||||
</div>
|
||||
<div className="text-xs text-green-800/80">
|
||||
{resumen.pagada.horas.toFixed(2)} h · {resumen.pagada.count} registro(s)
|
||||
{incluirIva ? " · IVA incluido" : ""}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="grid grid-cols-1 md:grid-cols-12 gap-2 items-end bg-gray-50 rounded-lg p-3 mb-4"
|
||||
>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs text-muted mb-1">Fecha</label>
|
||||
<input
|
||||
type="date"
|
||||
value={form.fecha}
|
||||
onChange={(e) => setForm({ ...form, fecha: e.target.value })}
|
||||
className={`${INPUT} w-full`}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-1">
|
||||
<label className="block text-xs text-muted mb-1">Inicio</label>
|
||||
<input
|
||||
type="time"
|
||||
value={form.horaInicio}
|
||||
onChange={(e) => setForm({ ...form, horaInicio: e.target.value })}
|
||||
className={`${INPUT} w-full`}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-1">
|
||||
<label className="block text-xs text-muted mb-1">Fin</label>
|
||||
<input
|
||||
type="time"
|
||||
value={form.horaFin}
|
||||
onChange={(e) => setForm({ ...form, horaFin: e.target.value })}
|
||||
className={`${INPUT} w-full`}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-1">
|
||||
<label className="block text-xs text-muted mb-1">Horas</label>
|
||||
<div className="px-2 py-1.5 text-sm font-medium text-center">
|
||||
{horasPreview > 0 ? horasPreview.toFixed(2) : "—"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="md:col-span-4">
|
||||
<label className="block text-xs text-muted mb-1">Descripcion</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.descripcion}
|
||||
onChange={(e) => setForm({ ...form, descripcion: e.target.value })}
|
||||
placeholder="Qué se hizo en este tramo"
|
||||
className={`${INPUT} w-full`}
|
||||
maxLength={500}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-1">
|
||||
<label className="block text-xs text-muted mb-1">Tarifa/hr</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
step={0.01}
|
||||
value={form.tarifaHora}
|
||||
onChange={(e) => setForm({ ...form, tarifaHora: parseFloat(e.target.value) || 0 })}
|
||||
className={`${INPUT} w-full text-right`}
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2 flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="flex-1 flex items-center justify-center gap-1 px-3 py-1.5 bg-primary text-white rounded-lg text-sm hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{editId ? <Pencil className="w-4 h-4" /> : <Plus className="w-4 h-4" />}
|
||||
{editId ? "Guardar" : "Agregar"}
|
||||
</button>
|
||||
{editId && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetForm}
|
||||
className="px-2 py-1.5 border border-border rounded-lg text-sm hover:bg-gray-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{error && <p className="md:col-span-12 text-sm text-red-600">{error}</p>}
|
||||
</form>
|
||||
|
||||
<div className="flex items-end gap-3 flex-wrap mb-3">
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Estado</label>
|
||||
<select
|
||||
value={estadoFiltro}
|
||||
onChange={(e) => setEstadoFiltro(e.target.value as FiltroEstado)}
|
||||
className={INPUT}
|
||||
>
|
||||
{FILTROS_ESTADO.map((f) => (
|
||||
<option key={f.value} value={f.value}>
|
||||
{f.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Desde</label>
|
||||
<input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className={INPUT} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs text-muted mb-1">Hasta</label>
|
||||
<input type="date" value={to} onChange={(e) => setTo(e.target.value)} className={INPUT} />
|
||||
</div>
|
||||
{(from || to) && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setFrom("");
|
||||
setTo("");
|
||||
}}
|
||||
className="text-xs text-muted underline py-2"
|
||||
>
|
||||
Limpiar
|
||||
</button>
|
||||
)}
|
||||
<div className="ml-auto">
|
||||
<label className="block text-xs text-muted mb-1">Desglose</label>
|
||||
<select
|
||||
value={modo}
|
||||
onChange={(e) => setModo(e.target.value as ModoAgrupacion)}
|
||||
className={INPUT}
|
||||
>
|
||||
{MODOS_AGRUPACION.map((m) => (
|
||||
<option key={m.value} value={m.value}>
|
||||
{m.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{filtrados.length === 0 ? (
|
||||
<div className="py-6 text-center">
|
||||
<p className="text-muted text-sm">
|
||||
{estadoFiltro === "pagada"
|
||||
? "No hay horas marcadas como pagadas"
|
||||
: estadoFiltro === "por_pagar"
|
||||
? "No hay horas pendientes de pago"
|
||||
: "Aún no hay registros de horas"}
|
||||
{from || to ? " en este periodo" : ""}.
|
||||
</p>
|
||||
{estadoFiltro === "por_pagar" && resumen.pagada.count > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEstadoFiltro("pagada")}
|
||||
className="mt-2 inline-flex items-center gap-1.5 text-sm text-primary hover:underline"
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
Ver {resumen.pagada.count} pagada(s) para editar o regresar a “Por pagar”
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-muted border-b border-border">
|
||||
{modo === "detalle" ? (
|
||||
<>
|
||||
<th className="py-2 pr-3 font-medium">Fecha</th>
|
||||
<th className="py-2 pr-3 font-medium">Horario</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Horas</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Tarifa</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Importe</th>
|
||||
<th className="py-2 pr-3 font-medium">Descripcion</th>
|
||||
<th className="py-2 pr-3 font-medium">Estado</th>
|
||||
<th className="py-2 font-medium"></th>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<th className="py-2 pr-3 font-medium">Periodo</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Registros</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Horas</th>
|
||||
<th className="py-2 pr-3 font-medium text-right">Importe</th>
|
||||
</>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{modo === "detalle"
|
||||
? filtrados.map((r) => (
|
||||
<tr
|
||||
key={r.id}
|
||||
className={`border-b border-border/60 ${esPagada(r.estadoPago) ? "bg-green-50/40" : ""}`}
|
||||
>
|
||||
<td className="py-2 pr-3 whitespace-nowrap">{formatFechaRegistro(new Date(r.fecha))}</td>
|
||||
<td className="py-2 pr-3 whitespace-nowrap">
|
||||
{r.horaInicio}–{r.horaFin}
|
||||
</td>
|
||||
<td className="py-2 pr-3 text-right">{r.horas.toFixed(2)}</td>
|
||||
<td className="py-2 pr-3 text-right">{formatCurrency(r.tarifaHora)}</td>
|
||||
<td className="py-2 pr-3 text-right">{formatCurrency(r.horas * r.tarifaHora)}</td>
|
||||
<td className="py-2 pr-3">{r.descripcion}</td>
|
||||
<td className="py-2 pr-3 whitespace-nowrap">{badgeEstado(r.estadoPago)}</td>
|
||||
<td className="py-2 text-right whitespace-nowrap">
|
||||
{esPagada(r.estadoPago) ? (
|
||||
<button
|
||||
onClick={() => regresarPorPagar(r)}
|
||||
disabled={togglingId === r.id}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded border border-amber-300 text-amber-700 hover:bg-amber-50 text-xs align-middle disabled:opacity-50"
|
||||
title="Regresar a Por pagar"
|
||||
>
|
||||
<RotateCcw className="w-3.5 h-3.5" />
|
||||
Por pagar
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => cambiarEstado(r, "pagada")}
|
||||
disabled={togglingId === r.id}
|
||||
className="inline-flex items-center gap-1 px-2 py-1 rounded border border-green-300 text-green-700 hover:bg-green-50 text-xs align-middle disabled:opacity-50"
|
||||
title="Marcar como pagada"
|
||||
>
|
||||
<CheckCircle2 className="w-3.5 h-3.5" />
|
||||
Pagada
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleEdit(r)}
|
||||
className="p-1 text-muted hover:text-primary align-middle"
|
||||
title="Editar"
|
||||
>
|
||||
<Pencil className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(r.id)}
|
||||
className="p-1 text-muted hover:text-red-600 align-middle"
|
||||
title="Eliminar"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
: grupos.map((g) => (
|
||||
<tr key={g.clave} className="border-b border-border/60">
|
||||
<td className="py-2 pr-3">{g.etiqueta}</td>
|
||||
<td className="py-2 pr-3 text-right">{g.count}</td>
|
||||
<td className="py-2 pr-3 text-right">{g.horas.toFixed(2)}</td>
|
||||
<td className="py-2 pr-3 text-right">{formatCurrency(g.importe)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{filtrados.length > 0 && (
|
||||
<div className="mt-4 pt-3 border-t border-border flex justify-end">
|
||||
<div className="w-full max-w-xs space-y-1 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">
|
||||
Total de horas{estadoFiltro !== "todas" ? ` (${FILTROS_ESTADO.find((f) => f.value === estadoFiltro)?.label.toLowerCase()})` : ""}
|
||||
</span>
|
||||
<span className="font-medium">{totalHoras.toFixed(2)} h</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">Subtotal</span>
|
||||
<span>{formatCurrency(subtotal)}</span>
|
||||
</div>
|
||||
{incluirIva && (
|
||||
<div className="flex justify-between text-muted">
|
||||
<span>IVA (16%)</span>
|
||||
<span>{formatCurrency(iva)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between font-bold pt-2 border-t border-border">
|
||||
<span>
|
||||
{estadoFiltro === "pagada"
|
||||
? "Total pagado"
|
||||
: estadoFiltro === "todas"
|
||||
? "Total general"
|
||||
: "Total a pagar"}
|
||||
</span>
|
||||
<span className="text-primary">{formatCurrency(total)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{previewHtml !== null && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex flex-col bg-black/60"
|
||||
onClick={() => setPreviewHtml(null)}
|
||||
>
|
||||
<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">{TITULO_NOTA[estadoFiltro]} — {numero}</h3>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<button
|
||||
onClick={descargarNotaPDF}
|
||||
disabled={descargando}
|
||||
className="flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4 text-primary" />
|
||||
{descargando ? "Generando…" : "Descargar PDF"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setPreviewHtml(null)}
|
||||
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
|
||||
ref={iframeRef}
|
||||
srcDoc={previewHtml}
|
||||
title="Previsualización de la nota de pago"
|
||||
className="w-full h-full rounded-lg bg-white border border-border"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { ArrowLeft, Download, FileText } from "lucide-react";
|
||||
import {
|
||||
IVA_RATE,
|
||||
conIva,
|
||||
calcularTotalesCotizacion,
|
||||
calcularTotalesOpcion,
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
type MetaOpcion,
|
||||
} from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
|
||||
const TIPO_PAGO_LABEL: Record<string, string> = {
|
||||
unico: "Único",
|
||||
mensual: "Mensual",
|
||||
};
|
||||
|
||||
interface ClienteCotizacionDetalle {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
fecha: string;
|
||||
vigencia: string;
|
||||
estado: string;
|
||||
moneda: string;
|
||||
esDoble: boolean;
|
||||
incluirIva: boolean;
|
||||
opcionesMetadata?: { "1"?: MetaOpcion; "2"?: MetaOpcion } | null;
|
||||
observaciones?: string | null;
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
planBucefalo?: { nivel: string; precio: number; seleccionado: boolean } | null;
|
||||
servicios: Array<{
|
||||
id: string;
|
||||
nombre: string | null;
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
seleccionado?: boolean;
|
||||
opcion?: string | null;
|
||||
servicioCatalogo?: { nombre: string } | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export function ClienteCotizacionDetallePage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [cot, setCot] = useState<ClienteCotizacionDetalle | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!id) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch(`/api/cliente/cotizaciones/${id}`, { credentials: "include" });
|
||||
if (res.status === 404) {
|
||||
setError("Cotización no encontrada");
|
||||
setCot(null);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error("No se pudo cargar la cotización");
|
||||
setCot(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !cot) return <LoadingScreen />;
|
||||
if (error || !cot) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Link
|
||||
to="/cliente/cotizaciones"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Volver a cotizaciones
|
||||
</Link>
|
||||
<PageError message={error || "Cotización no encontrada"} onRetry={load} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const serviciosNorm = cot.servicios.map((s) => ({
|
||||
...s,
|
||||
seleccionado: s.seleccionado ?? true,
|
||||
}));
|
||||
|
||||
const totales = calcularTotalesCotizacion(serviciosNorm, { incluirIva: cot.incluirIva });
|
||||
const opcionesMeta = cot.opcionesMetadata ?? {};
|
||||
const totalConIva = (monto: number) => conIva(monto, cot.incluirIva);
|
||||
|
||||
const gruposDoble = cot.esDoble
|
||||
? [
|
||||
{
|
||||
clave: "1",
|
||||
titulo: `Opción 1${opcionesMeta["1"]?.titulo ? `: ${opcionesMeta["1"].titulo}` : ""}`,
|
||||
descripcion: opcionesMeta["1"]?.descripcion,
|
||||
servicios: serviciosNorm.filter((s) => s.opcion === "1"),
|
||||
totales: calcularTotalesOpcion(serviciosNorm, "1"),
|
||||
},
|
||||
{
|
||||
clave: "2",
|
||||
titulo: `Opción 2${opcionesMeta["2"]?.titulo ? `: ${opcionesMeta["2"].titulo}` : ""}`,
|
||||
descripcion: opcionesMeta["2"]?.descripcion,
|
||||
servicios: serviciosNorm.filter((s) => s.opcion === "2"),
|
||||
totales: calcularTotalesOpcion(serviciosNorm, "2"),
|
||||
},
|
||||
{
|
||||
clave: "ambas",
|
||||
titulo: "Partidas compartidas",
|
||||
descripcion: undefined,
|
||||
servicios: serviciosNorm.filter((s) => s.opcion === "ambas" || !s.opcion),
|
||||
totales: null,
|
||||
},
|
||||
].filter((g) => g.servicios.length > 0)
|
||||
: [];
|
||||
|
||||
const serviciosVisibles = cot.esDoble ? [] : serviciosNorm.filter((s) => s.seleccionado);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-6">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Link
|
||||
to="/cliente/cotizaciones"
|
||||
className="p-2 hover:bg-gray-100 rounded-lg"
|
||||
aria-label="Volver a cotizaciones"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
</Link>
|
||||
<div className="min-w-0">
|
||||
<h1 className="text-2xl font-bold tracking-tight">{cot.numero}</h1>
|
||||
<p className="text-muted text-sm truncate">
|
||||
{cot.proyecto} · {formatDate(new Date(cot.fecha))}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<EstadoBadge estado={cot.estado} />
|
||||
<a
|
||||
href={`/api/export/pdf/${cot.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
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"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Descargar PDF
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6">
|
||||
<h2 className="font-semibold text-lg mb-4">Información general</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">Vigencia</span>
|
||||
<p className="font-medium">{formatDate(new Date(cot.vigencia))}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted">Moneda</span>
|
||||
<p className="font-medium">{cot.moneda}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cot.planBucefalo?.seleccionado && (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mb-6 flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<FileText className="w-4 h-4 text-primary" />
|
||||
Plan Bucéfalo
|
||||
</h3>
|
||||
<p className="text-sm text-muted mt-1 capitalize">
|
||||
Nivel {cot.planBucefalo.nivel} · CRM para tu operación
|
||||
</p>
|
||||
</div>
|
||||
<p className="font-semibold">{formatCurrency(cot.planBucefalo.precio)}/mes</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cot.esDoble ? (
|
||||
<div className="space-y-6 mb-6">
|
||||
{gruposDoble.map((g) => (
|
||||
<div
|
||||
key={g.clave}
|
||||
className="bg-card-bg rounded-xl border border-border overflow-hidden"
|
||||
>
|
||||
<div className="px-5 py-4 border-b border-border bg-primary-light/20">
|
||||
<h2 className="font-semibold text-lg text-primary">{g.titulo}</h2>
|
||||
{g.descripcion && (
|
||||
<p className="text-sm text-muted mt-1 whitespace-pre-wrap">
|
||||
{g.descripcion}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<table className="w-full text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Servicio</th>
|
||||
<th className="hidden sm:table-cell text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{g.servicios.map((s) => (
|
||||
<tr key={s.id} className="border-b border-border last:border-0">
|
||||
<td className="px-5 py-3">
|
||||
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
||||
<span className="block text-xs text-muted sm:hidden">
|
||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden sm:table-cell px-5 py-3 text-muted">
|
||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-medium">
|
||||
{formatCurrency(s.precio)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{g.totales && (
|
||||
<div className="px-5 py-4 border-t border-border grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-2 text-sm tabular-nums">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">Total único{cot.incluirIva ? " (c/IVA)" : ""}</span>
|
||||
<span className="font-semibold">
|
||||
{formatCurrency(totalConIva(g.totales.totalUnico))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">Total mensual{cot.incluirIva ? " (c/IVA)" : ""}</span>
|
||||
<span className="font-semibold">
|
||||
{formatCurrency(totalConIva(g.totales.totalMensual))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden mb-6">
|
||||
<div className="px-5 py-4 border-b border-border">
|
||||
<h2 className="font-semibold text-lg">Servicios</h2>
|
||||
</div>
|
||||
{serviciosVisibles.length === 0 ? (
|
||||
<div className="p-8 text-center text-muted text-sm">
|
||||
Esta cotización no tiene servicios registrados.
|
||||
</div>
|
||||
) : (
|
||||
<table className="w-full text-sm tabular-nums">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-gray-50">
|
||||
<th className="text-left px-5 py-3 font-medium text-muted">Servicio</th>
|
||||
<th className="hidden sm:table-cell text-left px-5 py-3 font-medium text-muted">Tipo de pago</th>
|
||||
<th className="text-right px-5 py-3 font-medium text-muted">Precio</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{serviciosVisibles.map((s) => (
|
||||
<tr key={s.id} className="border-b border-border hover:bg-gray-50 transition-colors">
|
||||
<td className="px-5 py-3">
|
||||
{s.servicioCatalogo?.nombre || s.nombre || "Servicio"}
|
||||
<span className="block text-xs text-muted sm:hidden">
|
||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||
</span>
|
||||
</td>
|
||||
<td className="hidden sm:table-cell px-5 py-3 text-muted">
|
||||
{TIPO_PAGO_LABEL[s.tipoPago] || s.tipoPago}
|
||||
</td>
|
||||
<td className="px-5 py-3 text-right font-medium">
|
||||
{formatCurrency(s.precio)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5">
|
||||
<h2 className="font-semibold text-lg mb-4">Totales</h2>
|
||||
{cot.esDoble ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{(["1", "2"] as const).map((op) => {
|
||||
const t = calcularTotalesOpcion(serviciosNorm, 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">
|
||||
Opción {op}
|
||||
{meta?.titulo ? `: ${meta.titulo}` : ""}
|
||||
</h3>
|
||||
<div className="mt-3 space-y-1 text-sm tabular-nums">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">
|
||||
Total único{cot.incluirIva ? " (c/IVA)" : ""}
|
||||
</span>
|
||||
<span className="font-semibold">
|
||||
{formatCurrency(totalConIva(t.totalUnico))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">
|
||||
Total mensual{cot.incluirIva ? " (c/IVA)" : ""}
|
||||
</span>
|
||||
<span className="font-semibold">
|
||||
{formatCurrency(totalConIva(t.totalMensual))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-w-sm space-y-2 text-sm tabular-nums">
|
||||
{totales.incluyeIva && (
|
||||
<>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">Subtotal único</span>
|
||||
<span>{formatCurrency(totales.subtotalUnico)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">IVA ({Math.round(IVA_RATE * 100)}%)</span>
|
||||
<span>{formatCurrency(totales.ivaUnico)}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
|
||||
<span>Total único</span>
|
||||
<span>{formatCurrency(totales.totalUnico)}</span>
|
||||
</div>
|
||||
{totales.incluyeIva && (
|
||||
<>
|
||||
<div className="flex justify-between pt-2">
|
||||
<span className="text-muted">Subtotal mensual</span>
|
||||
<span>{formatCurrency(totales.subtotalMensual)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted">IVA ({Math.round(IVA_RATE * 100)}%)</span>
|
||||
<span>{formatCurrency(totales.ivaMensual)}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="flex justify-between font-semibold text-base border-t border-border pt-2">
|
||||
<span>Total mensual</span>
|
||||
<span>{formatCurrency(totales.totalMensual)}</span>
|
||||
</div>
|
||||
{!totales.incluyeIva && (
|
||||
<p className="text-xs text-muted">Los precios no incluyen IVA.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{cot.observaciones && (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 mt-6">
|
||||
<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,111 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { FileText } from "lucide-react";
|
||||
import { calcularTotalesCotizacion, calcularTotalesOpcion, conIva } from "@/lib/calculators";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { FilaCotizacion } from "./FilaCotizacion";
|
||||
|
||||
interface ClienteCotizacionRow {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
fecha: string;
|
||||
estado: string;
|
||||
esDoble: boolean;
|
||||
incluirIva: boolean;
|
||||
servicios?: Array<{
|
||||
tipoPago: string;
|
||||
precio: number;
|
||||
seleccionado?: boolean;
|
||||
opcion?: string | null;
|
||||
}>;
|
||||
totales?: { totalUnico: number; totalMensual: number };
|
||||
totalesOpciones?: {
|
||||
"1": { totalUnico: number; totalMensual: number };
|
||||
"2": { totalUnico: number; totalMensual: number };
|
||||
} | null;
|
||||
}
|
||||
|
||||
export function ClienteCotizacionesPage() {
|
||||
const [cotizaciones, setCotizaciones] = useState<ClienteCotizacionRow[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/cliente/cotizaciones", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudieron cargar tus cotizaciones");
|
||||
setCotizaciones(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !cotizaciones) return <LoadingScreen />;
|
||||
if (error || !cotizaciones) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Mis cotizaciones</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
{cotizaciones.length === 0
|
||||
? "Aún no tienes cotizaciones"
|
||||
: `${cotizaciones.length} ${cotizaciones.length === 1 ? "cotización" : "cotizaciones"} a tu nombre`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{cotizaciones.length === 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<FileText className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold mb-2">No hay cotizaciones todavía</h2>
|
||||
<p className="text-muted">
|
||||
Cuando tengas una cotización disponible aparecerá en esta sección.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="bg-card-bg rounded-xl border border-border divide-y divide-border overflow-hidden">
|
||||
{cotizaciones.map((c) => {
|
||||
const servicios = (c.servicios ?? []).map((s) => ({
|
||||
...s,
|
||||
seleccionado: s.seleccionado ?? true,
|
||||
}));
|
||||
const totales =
|
||||
c.totales ?? calcularTotalesCotizacion(servicios, { incluirIva: c.incluirIva });
|
||||
const opciones = c.esDoble
|
||||
? (["1", "2"] as const).map((op) => {
|
||||
const t = c.totalesOpciones?.[op] ?? calcularTotalesOpcion(servicios, op);
|
||||
return {
|
||||
clave: op,
|
||||
montos: {
|
||||
unico: conIva(t.totalUnico, c.incluirIva),
|
||||
mensual: conIva(t.totalMensual, c.incluirIva),
|
||||
},
|
||||
};
|
||||
})
|
||||
: undefined;
|
||||
return (
|
||||
<FilaCotizacion
|
||||
key={c.id}
|
||||
id={c.id}
|
||||
numero={c.numero}
|
||||
proyecto={c.proyecto}
|
||||
fecha={c.fecha}
|
||||
estado={c.estado}
|
||||
montos={{ unico: totales.totalUnico, mensual: totales.totalMensual }}
|
||||
opciones={opciones}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { ArrowRight, CalendarClock, CircleCheck, Clock3, FileText, Inbox } from "lucide-react";
|
||||
import { conIva } from "@/lib/calculators";
|
||||
import {
|
||||
describirVencimiento,
|
||||
diasHasta,
|
||||
formatFechaBreve,
|
||||
formatMonto,
|
||||
formatTotales,
|
||||
hoyCalendario,
|
||||
} from "@/lib/cobros-fechas";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { FilaCotizacion } from "./FilaCotizacion";
|
||||
|
||||
interface ResumenCotizacion {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
fecha: string;
|
||||
estado: string;
|
||||
incluirIva: boolean;
|
||||
totales: { totalUnico: number; totalMensual: number };
|
||||
totalesOpciones?: {
|
||||
"1": { totalUnico: number; totalMensual: number };
|
||||
"2": { totalUnico: number; totalMensual: number };
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface ResumenClienteData {
|
||||
cliente: { nombre: string; empresa: string | null };
|
||||
cotizacionesActivas?: number;
|
||||
cotizaciones: ResumenCotizacion[];
|
||||
pagos: {
|
||||
pendientes: number;
|
||||
saldoPendiente: Record<string, number>;
|
||||
masAntiguo: string | null;
|
||||
enRevision: number;
|
||||
verificadosMes: number;
|
||||
proximos: Array<{
|
||||
fecha: string;
|
||||
monto: number;
|
||||
moneda: string;
|
||||
concepto: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export function ClienteInicioPage() {
|
||||
const [resumen, setResumen] = useState<ResumenClienteData | null>(null);
|
||||
const [sinCliente, setSinCliente] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setSinCliente(false);
|
||||
try {
|
||||
const res = await fetch("/api/cliente/resumen", { credentials: "include" });
|
||||
if (res.status === 404) {
|
||||
setSinCliente(true);
|
||||
setResumen(null);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error("No se pudo cargar tu resumen");
|
||||
setResumen(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !resumen && !sinCliente) return <LoadingScreen />;
|
||||
|
||||
if (sinCliente) {
|
||||
return (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<Inbox className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold mb-2">Cuenta sin cliente asociado</h2>
|
||||
<p className="text-muted">
|
||||
Tu usuario no tiene un cliente vinculado. Contacta al administrador para
|
||||
darlo de alta.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !resumen) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
const hoy = hoyCalendario();
|
||||
const { pagos } = resumen;
|
||||
const debe = pagos.pendientes > 0;
|
||||
const masAntiguoDate = pagos.masAntiguo ? new Date(pagos.masAntiguo) : null;
|
||||
const proximos = pagos.proximos.map((p) => ({ ...p, fechaDate: new Date(p.fecha) }));
|
||||
const proximo = proximos[0];
|
||||
|
||||
const indicadores = [
|
||||
{ label: "En revisión", value: pagos.enRevision },
|
||||
{ label: "Verificados este mes", value: pagos.verificadosMes },
|
||||
{
|
||||
label: "Cotizaciones activas",
|
||||
value: resumen.cotizacionesActivas ?? resumen.cotizaciones.length,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Hola, {resumen.cliente.nombre}</h1>
|
||||
{resumen.cliente.empresa && (
|
||||
<p className="text-muted text-sm mt-1">{resumen.cliente.empresa}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<section
|
||||
aria-label="Estado de tus pagos"
|
||||
className="bg-card-bg rounded-xl border border-border overflow-hidden mb-8"
|
||||
>
|
||||
<div className="flex flex-col gap-5 p-5 sm:flex-row sm:items-center sm:justify-between sm:p-6">
|
||||
{debe ? (
|
||||
<div className="flex items-start gap-4">
|
||||
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-amber-50 text-amber-600">
|
||||
<Clock3 className="w-6 h-6" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="font-semibold">
|
||||
Tienes {pagos.pendientes} {pagos.pendientes === 1 ? "pago pendiente" : "pagos pendientes"}
|
||||
</h2>
|
||||
<p className="text-2xl font-bold tracking-tight tabular-nums mt-1">
|
||||
{formatTotales(pagos.saldoPendiente)}
|
||||
</p>
|
||||
{masAntiguoDate && (
|
||||
<p className="text-sm text-muted mt-1">
|
||||
El más antiguo es del {formatFechaBreve(masAntiguoDate, hoy)}
|
||||
{diasHasta(masAntiguoDate, hoy) <= 0 &&
|
||||
` (${describirVencimiento(masAntiguoDate, hoy)})`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-start gap-4">
|
||||
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-green-50 text-green-600">
|
||||
<CircleCheck className="w-6 h-6" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 className="font-semibold">Estás al día con tus pagos</h2>
|
||||
<p className="text-sm text-muted mt-1">
|
||||
{proximo
|
||||
? `Tu próximo cobro es el ${formatFechaBreve(proximo.fechaDate, hoy)} por ${formatMonto(proximo.monto, proximo.moneda)}.`
|
||||
: "No tienes cobros pendientes."}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Link
|
||||
to="/cliente/pagos"
|
||||
className={`inline-flex shrink-0 items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-medium transition-colors ${
|
||||
debe
|
||||
? "bg-primary text-white hover:bg-primary-dark"
|
||||
: "border border-border hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{debe ? "Pagar y subir comprobante" : "Ver mis pagos"}
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</div>
|
||||
<dl className="grid grid-cols-3 divide-x divide-border border-t border-border bg-gray-50/60">
|
||||
{indicadores.map((i) => (
|
||||
<div key={i.label} className="px-4 py-3 sm:px-6">
|
||||
<dt className="text-xs text-muted">{i.label}</dt>
|
||||
<dd className="text-lg font-semibold tabular-nums">{i.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section className="bg-card-bg rounded-xl border border-border mb-8">
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h2 className="font-semibold flex items-center gap-2">
|
||||
<CalendarClock className="w-5 h-5 text-primary" />
|
||||
Próximos cobros
|
||||
</h2>
|
||||
<Link
|
||||
to="/cliente/pagos"
|
||||
className="text-sm text-primary hover:underline underline-offset-2 flex items-center gap-1"
|
||||
>
|
||||
Ver todos
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</div>
|
||||
{proximos.length === 0 ? (
|
||||
<p className="px-5 py-8 text-center text-sm text-muted">
|
||||
No tienes cobros programados por ahora.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border">
|
||||
{proximos.map((p) => (
|
||||
<li
|
||||
key={`${p.concepto}-${p.fecha}`}
|
||||
className="flex items-center justify-between gap-3 px-5 py-3"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium text-sm truncate">{p.concepto}</p>
|
||||
<p className="text-xs text-muted">
|
||||
{formatFechaBreve(p.fechaDate, hoy)} · {describirVencimiento(p.fechaDate, hoy)}
|
||||
</p>
|
||||
</div>
|
||||
<p className="font-semibold tabular-nums">{formatMonto(p.monto, p.moneda)}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="bg-card-bg rounded-xl border border-border">
|
||||
<div className="px-5 py-4 border-b border-border flex items-center justify-between">
|
||||
<h2 className="font-semibold flex items-center gap-2">
|
||||
<FileText className="w-5 h-5 text-primary" />
|
||||
Últimas cotizaciones
|
||||
</h2>
|
||||
<Link
|
||||
to="/cliente/cotizaciones"
|
||||
className="text-sm text-primary hover:underline underline-offset-2 flex items-center gap-1"
|
||||
>
|
||||
Ver todas
|
||||
<ArrowRight className="w-4 h-4" />
|
||||
</Link>
|
||||
</div>
|
||||
{resumen.cotizaciones.length === 0 ? (
|
||||
<p className="px-5 py-8 text-center text-sm text-muted">
|
||||
Todavía no tienes cotizaciones. En cuanto el administrador la envíe, aparecerá aquí.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border">
|
||||
{resumen.cotizaciones.map((c) => (
|
||||
<FilaCotizacion
|
||||
key={c.id}
|
||||
id={c.id}
|
||||
numero={c.numero}
|
||||
proyecto={c.proyecto}
|
||||
fecha={c.fecha}
|
||||
estado={c.estado}
|
||||
montos={{ unico: c.totales.totalUnico, mensual: c.totales.totalMensual }}
|
||||
opciones={
|
||||
c.totalesOpciones
|
||||
? (["1", "2"] as const).map((op) => ({
|
||||
clave: op,
|
||||
montos: {
|
||||
unico: conIva(c.totalesOpciones![op].totalUnico, c.incluirIva),
|
||||
mensual: conIva(c.totalesOpciones![op].totalMensual, c.incluirIva),
|
||||
},
|
||||
}))
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Check, CircleCheck, Clock3, FileText, Inbox, Minus } from "lucide-react";
|
||||
import {
|
||||
ESTADOS_PAGO,
|
||||
describirVencimiento,
|
||||
diasHasta,
|
||||
esPorPagar,
|
||||
formatFechaBreve,
|
||||
formatMonto,
|
||||
formatTotales,
|
||||
hoyCalendario,
|
||||
proximaFecha,
|
||||
totalesPorMoneda,
|
||||
} from "@/lib/cobros-fechas";
|
||||
import { LoadingScreen, PageError } from "@/components/ui/LoadingScreen";
|
||||
import { SubirComprobante } from "./SubirComprobante";
|
||||
import { CopiarDato } from "./CopiarDato";
|
||||
|
||||
const DIAS_SEMANA = [
|
||||
"domingo",
|
||||
"lunes",
|
||||
"martes",
|
||||
"miércoles",
|
||||
"jueves",
|
||||
"viernes",
|
||||
"sábado",
|
||||
];
|
||||
|
||||
const HISTORIAL_VISIBLE = 4;
|
||||
|
||||
interface PagoClienteAPI {
|
||||
id: string;
|
||||
programaId?: string;
|
||||
fecha: string;
|
||||
monto: number;
|
||||
estado: string;
|
||||
rechazoMotivo?: string | null;
|
||||
comprobante: { archivoNombre: string } | null;
|
||||
}
|
||||
|
||||
interface ProgramaClienteAPI {
|
||||
id: string;
|
||||
concepto: string;
|
||||
monto: number;
|
||||
moneda: string;
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
activo: boolean;
|
||||
fechaInicio: string;
|
||||
fechaFin?: string | null;
|
||||
pagos?: PagoClienteAPI[];
|
||||
}
|
||||
|
||||
interface ClientePagosResponse {
|
||||
pagos: PagoClienteAPI[];
|
||||
programas: ProgramaClienteAPI[];
|
||||
bancaria: Record<string, string>;
|
||||
}
|
||||
|
||||
function frecuenciaLegible(p: {
|
||||
frecuencia: string;
|
||||
diaSemana?: number | null;
|
||||
diaMes?: number | null;
|
||||
}): string {
|
||||
if (p.frecuencia === "semanal") return `cada ${DIAS_SEMANA[p.diaSemana ?? 0]}`;
|
||||
if (p.frecuencia === "quincenal") return "los días 1 y 15";
|
||||
if (p.frecuencia === "mensual") return `el día ${p.diaMes ?? 1} de cada mes`;
|
||||
return p.frecuencia;
|
||||
}
|
||||
|
||||
function EstadoHistorial({ estado }: { estado: string }) {
|
||||
if (estado === ESTADOS_PAGO.ANULADO) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
|
||||
<Minus className="w-3 h-3" />
|
||||
Sin cargo
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (estado === ESTADOS_PAGO.VERIFICADO) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-2.5 py-0.5 text-xs font-medium text-green-700">
|
||||
<Check className="w-3 h-3" />
|
||||
Verificado
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
|
||||
<Clock3 className="w-3 h-3" />
|
||||
En revisión
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
type FilaHistorial = {
|
||||
id: string;
|
||||
fecha: Date;
|
||||
monto: number;
|
||||
estado: string;
|
||||
comprobante: { archivoNombre: string } | null;
|
||||
};
|
||||
|
||||
function FilaPago({ pago, moneda, hoy }: { pago: FilaHistorial; moneda: string; hoy: Date }) {
|
||||
return (
|
||||
<li className="flex flex-wrap items-center gap-x-4 gap-y-1.5 px-5 py-3 text-sm">
|
||||
<span className="w-28 shrink-0">{formatFechaBreve(pago.fecha, hoy)}</span>
|
||||
<EstadoHistorial estado={pago.estado} />
|
||||
<span className="ml-auto font-medium tabular-nums">{formatMonto(pago.monto, moneda)}</span>
|
||||
{pago.comprobante ? (
|
||||
<a
|
||||
href={`/api/comprobantes/${pago.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary hover:underline underline-offset-2"
|
||||
title={pago.comprobante.archivoNombre}
|
||||
>
|
||||
<FileText className="w-3.5 h-3.5" />
|
||||
Comprobante
|
||||
</a>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function ClientePagosPage() {
|
||||
const [data, setData] = useState<ClientePagosResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetch("/api/cliente/pagos", { credentials: "include" });
|
||||
if (!res.ok) throw new Error("No se pudieron cargar tus pagos");
|
||||
setData(await res.json());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Error de conexión");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
if (loading && !data) return <LoadingScreen />;
|
||||
if (error || !data) return <PageError message={error || "Error al cargar"} onRetry={load} />;
|
||||
|
||||
const banco = data.bancaria ?? {};
|
||||
const pagosSueltos = Array.isArray(data.pagos) ? data.pagos : [];
|
||||
const programas = (Array.isArray(data.programas) ? data.programas : []).map((prog) => {
|
||||
const listaPagos = Array.isArray(prog.pagos)
|
||||
? prog.pagos
|
||||
: pagosSueltos.filter((p) => p.programaId === prog.id);
|
||||
const pagosConFecha = listaPagos
|
||||
.map((p) => ({ ...p, fecha: new Date(p.fecha) }))
|
||||
.sort((a, b) => b.fecha.getTime() - a.fecha.getTime());
|
||||
return { ...prog, pagos: pagosConFecha };
|
||||
});
|
||||
|
||||
const hoy = hoyCalendario();
|
||||
|
||||
const porPagar = programas
|
||||
.flatMap((prog) =>
|
||||
prog.pagos
|
||||
.filter((pago) => esPorPagar(pago.estado))
|
||||
.map((pago) => ({ ...pago, programa: { concepto: prog.concepto, moneda: prog.moneda } }))
|
||||
)
|
||||
.sort((a, b) => a.fecha.getTime() - b.fecha.getTime());
|
||||
|
||||
const enRevision = programas.reduce(
|
||||
(n, prog) => n + prog.pagos.filter((p) => p.estado === ESTADOS_PAGO.EN_REVISION).length,
|
||||
0
|
||||
);
|
||||
|
||||
const datosPago = [
|
||||
["Titular", banco.razon_social],
|
||||
["CLABE", banco.clabe_interbancaria],
|
||||
["Cuenta", banco.cuenta_nacional],
|
||||
].filter((par): par is [string, string] => Boolean(par[1]));
|
||||
|
||||
if (programas.length === 0) {
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight mb-8">Mis pagos</h1>
|
||||
<div className="bg-card-bg rounded-xl border border-border p-12 text-center">
|
||||
<Inbox className="w-12 h-12 text-muted mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold mb-2">Sin cobros programados</h2>
|
||||
<p className="text-muted max-w-md mx-auto">
|
||||
Cuando se configure un programa de pagos para ti, aparecerá aquí junto con cada
|
||||
cobro generado.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Mis pagos</h1>
|
||||
<p className="text-muted text-sm mt-1">
|
||||
Paga tus cobros y sube el comprobante para que quede registrado.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_18rem]">
|
||||
<section aria-labelledby="titulo-por-pagar" className="min-w-0 lg:col-start-1 lg:row-start-1">
|
||||
{porPagar.length > 0 ? (
|
||||
<div className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 px-5 py-4 border-b border-border">
|
||||
<h2 id="titulo-por-pagar" className="text-lg font-semibold">
|
||||
Por pagar
|
||||
</h2>
|
||||
<p className="text-sm text-muted">
|
||||
{porPagar.length} {porPagar.length === 1 ? "cobro" : "cobros"} ·{" "}
|
||||
<span className="font-semibold text-foreground tabular-nums">
|
||||
{formatTotales(totalesPorMoneda(porPagar))}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<ul className="divide-y divide-border">
|
||||
{porPagar.map((pago) => {
|
||||
const vencido = diasHasta(pago.fecha, hoy) < 0;
|
||||
const rechazado = pago.estado === ESTADOS_PAGO.RECHAZADO;
|
||||
return (
|
||||
<li
|
||||
key={pago.id}
|
||||
className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="font-medium">{pago.programa.concepto}</p>
|
||||
<p className="text-sm text-muted mt-0.5">
|
||||
{formatFechaBreve(pago.fecha, hoy)} ·{" "}
|
||||
<span className={vencido ? "font-medium text-red-600" : "font-medium text-amber-700"}>
|
||||
{describirVencimiento(pago.fecha, hoy)}
|
||||
</span>
|
||||
</p>
|
||||
{rechazado && (
|
||||
<p className="text-sm text-red-700 mt-1.5">
|
||||
Rechazamos el comprobante
|
||||
{pago.rechazoMotivo ? `: ${pago.rechazoMotivo}` : ""}. Sube uno nuevo.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-4 sm:justify-end">
|
||||
<span className="text-lg font-semibold tabular-nums">
|
||||
{formatMonto(pago.monto, pago.programa.moneda)}
|
||||
</span>
|
||||
<SubirComprobante pagoId={pago.id} variante="primario" onUploaded={load} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-card-bg rounded-xl border border-border p-5 flex items-center gap-4">
|
||||
<span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-green-50 text-green-600">
|
||||
<CircleCheck className="w-6 h-6" />
|
||||
</span>
|
||||
<div>
|
||||
<h2 id="titulo-por-pagar" className="font-semibold">
|
||||
Estás al día
|
||||
</h2>
|
||||
<p className="text-sm text-muted">
|
||||
No tienes cobros pendientes de pago.
|
||||
{enRevision > 0 &&
|
||||
` ${enRevision} ${enRevision === 1 ? "comprobante está" : "comprobantes están"} en revisión.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<aside className="space-y-4 lg:col-start-2 lg:row-start-1 lg:row-span-2 lg:self-start lg:sticky lg:top-32">
|
||||
{datosPago.length > 0 && (
|
||||
<div className="bg-card-bg rounded-xl border border-border px-5 py-4">
|
||||
<h2 className="font-semibold mb-1">Datos para tu pago</h2>
|
||||
<div className="divide-y divide-border">
|
||||
{datosPago.map(([etiqueta, valor]) => (
|
||||
<CopiarDato key={etiqueta} etiqueta={etiqueta} valor={valor} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-card-bg rounded-xl border border-border px-5 py-4 text-sm">
|
||||
<h2 className="font-semibold mb-2">Cómo se registra tu pago</h2>
|
||||
<ol className="list-decimal space-y-1.5 pl-4 text-muted marker:text-muted">
|
||||
<li>Haz la transferencia por el monto del cobro.</li>
|
||||
<li>Sube el comprobante (imagen o PDF, hasta 10 MB) en ese cobro.</li>
|
||||
<li>Lo revisamos y te avisamos cuando quede verificado.</li>
|
||||
</ol>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section aria-labelledby="titulo-historial" className="min-w-0 lg:col-start-1 lg:row-start-2">
|
||||
<h2 id="titulo-historial" className="text-lg font-semibold mb-3 mt-2">
|
||||
Historial
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{programas.map((prog) => {
|
||||
const registrados = prog.pagos.filter((p) => !esPorPagar(p.estado));
|
||||
const visibles = registrados.slice(0, HISTORIAL_VISIBLE);
|
||||
const anteriores = registrados.slice(HISTORIAL_VISIBLE);
|
||||
const proximo = prog.activo ? proximaFecha(prog, hoy) : null;
|
||||
return (
|
||||
<div key={prog.id} className="bg-card-bg rounded-xl border border-border overflow-hidden">
|
||||
<div className="flex flex-wrap items-start justify-between gap-2 px-5 py-4 border-b border-border">
|
||||
<div className="min-w-0">
|
||||
<h3 className="font-semibold">{prog.concepto}</h3>
|
||||
<p className="text-sm text-muted mt-0.5">
|
||||
<span className="tabular-nums">{formatMonto(prog.monto, prog.moneda)}</span>{" "}
|
||||
{frecuenciaLegible(prog)}
|
||||
{proximo && ` · próximo: ${formatFechaBreve(proximo, hoy)}`}
|
||||
</p>
|
||||
</div>
|
||||
{!prog.activo && (
|
||||
<span className="rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600">
|
||||
Programa inactivo
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{registrados.length === 0 ? (
|
||||
<p className="px-5 py-4 text-sm text-muted">Aún no hay pagos registrados.</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="divide-y divide-border">
|
||||
{visibles.map((pago) => (
|
||||
<FilaPago key={pago.id} pago={pago} moneda={prog.moneda} hoy={hoy} />
|
||||
))}
|
||||
</ul>
|
||||
{anteriores.length > 0 && (
|
||||
<details className="group border-t border-border">
|
||||
<summary className="cursor-pointer list-none px-5 py-3 text-sm font-medium text-primary hover:bg-gray-50 [&::-webkit-details-marker]:hidden">
|
||||
<span className="group-open:hidden">
|
||||
Ver {anteriores.length} {anteriores.length === 1 ? "pago anterior" : "pagos anteriores"}
|
||||
</span>
|
||||
<span className="hidden group-open:inline">Ocultar pagos anteriores</span>
|
||||
</summary>
|
||||
<ul className="divide-y divide-border border-t border-border">
|
||||
{anteriores.map((pago) => (
|
||||
<FilaPago key={pago.id} pago={pago} moneda={prog.moneda} hoy={hoy} />
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useLocation, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
Bell,
|
||||
BellRing,
|
||||
CreditCard,
|
||||
FileText,
|
||||
Home,
|
||||
LogOut,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
const NAV = [
|
||||
{ href: "/cliente", label: "Inicio", icon: Home },
|
||||
{ href: "/cliente/cotizaciones", label: "Cotizaciones", icon: FileText },
|
||||
{ href: "/cliente/pagos", label: "Pagos", icon: CreditCard },
|
||||
];
|
||||
|
||||
function esActiva(pathname: string, href: string): boolean {
|
||||
if (href === "/cliente") return pathname === href;
|
||||
return pathname === href || pathname.startsWith(href + "/");
|
||||
}
|
||||
|
||||
export function ClienteShell({ nombre }: { nombre: string }) {
|
||||
const { pathname } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const { setUser } = useAuth();
|
||||
const toast = useToast();
|
||||
const [activas, setActivas] = useState(false);
|
||||
const [activando, setActivando] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelado = false;
|
||||
(async () => {
|
||||
try {
|
||||
if (
|
||||
"serviceWorker" in navigator &&
|
||||
"PushManager" in window &&
|
||||
typeof Notification !== "undefined" &&
|
||||
Notification.permission === "granted"
|
||||
) {
|
||||
const reg = await navigator.serviceWorker.register("/sw.js");
|
||||
const sub = await reg.pushManager.getSubscription();
|
||||
if (!cancelado && sub) setActivas(true);
|
||||
}
|
||||
} catch {
|
||||
// Sin subscription previa el boton sigue disponible para activar.
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelado = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const cerrarSesion = async () => {
|
||||
try {
|
||||
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
|
||||
} catch {
|
||||
// Aunque falle la peticion, limpiamos la navegacion local.
|
||||
}
|
||||
setUser(null);
|
||||
navigate("/login?panel=cliente", { replace: true });
|
||||
};
|
||||
|
||||
const activarNotificaciones = async () => {
|
||||
if (activando || activas) return;
|
||||
setActivando(true);
|
||||
try {
|
||||
if (
|
||||
!("serviceWorker" in navigator) ||
|
||||
!("PushManager" in window) ||
|
||||
typeof Notification === "undefined"
|
||||
) {
|
||||
toast("Las notificaciones no están disponibles", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch("/api/cliente/push/config");
|
||||
if (res.status === 401 || res.status === 501) {
|
||||
toast("Las notificaciones no están disponibles", "error");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) {
|
||||
toast("Las notificaciones no están disponibles", "error");
|
||||
return;
|
||||
}
|
||||
const data = (await res.json()) as { publicKey?: string };
|
||||
if (!data.publicKey) {
|
||||
toast("Las notificaciones no están disponibles", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Notification.permission === "denied") {
|
||||
toast(
|
||||
"El navegador bloqueó las notificaciones. Actívalas en la configuración del sitio.",
|
||||
"error"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let permiso: NotificationPermission = Notification.permission;
|
||||
if (permiso === "default") {
|
||||
permiso = await Notification.requestPermission();
|
||||
}
|
||||
if (permiso !== "granted") {
|
||||
toast("No se otorgó el permiso de notificaciones", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const reg = await navigator.serviceWorker.register("/sw.js");
|
||||
let sub = await reg.pushManager.getSubscription();
|
||||
if (!sub) {
|
||||
sub = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: data.publicKey,
|
||||
});
|
||||
}
|
||||
|
||||
const json = sub.toJSON();
|
||||
if (!json.endpoint || !json.keys?.p256dh || !json.keys?.auth) {
|
||||
toast("No se pudo registrar la suscripción", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const guardar = await fetch("/api/cliente/push/suscribir", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
endpoint: json.endpoint,
|
||||
p256dh: json.keys.p256dh,
|
||||
auth: json.keys.auth,
|
||||
}),
|
||||
});
|
||||
if (!guardar.ok) {
|
||||
const err = (await guardar.json().catch(() => ({}))) as { error?: string };
|
||||
toast(err.error || "No se pudieron activar las notificaciones", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
setActivas(true);
|
||||
toast("Notificaciones activadas", "success");
|
||||
} catch {
|
||||
toast("No se pudieron activar las notificaciones", "error");
|
||||
} finally {
|
||||
setActivando(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-40 bg-card-bg border-b border-border">
|
||||
<div className="mx-auto max-w-5xl px-4 lg:px-8">
|
||||
<div className="flex h-16 items-center justify-between gap-3">
|
||||
<Link to="/cliente" className="flex items-center gap-2.5 min-w-0">
|
||||
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary text-white">
|
||||
<Sparkles className="w-4 h-4" />
|
||||
</span>
|
||||
<span className="min-w-0">
|
||||
<span className="block font-bold leading-tight truncate">Cotizador — Uriel Jareth Consulting</span>
|
||||
<span className="block text-xs text-muted truncate">{nombre}</span>
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={activarNotificaciones}
|
||||
disabled={activas || activando}
|
||||
aria-label={activas ? "Notificaciones activas" : "Activar notificaciones"}
|
||||
title={activas ? "Recibirás avisos de cobros en este navegador" : "Recibe avisos de cobros en este navegador"}
|
||||
className={`flex items-center gap-1.5 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
||||
activas
|
||||
? "border-green-200 bg-green-50 text-green-700 cursor-default"
|
||||
: "border-border hover:bg-gray-50 disabled:opacity-60"
|
||||
}`}
|
||||
>
|
||||
{activas ? (
|
||||
<BellRing className="w-4 h-4" />
|
||||
) : (
|
||||
<Bell className="w-4 h-4" />
|
||||
)}
|
||||
<span className="hidden sm:inline">
|
||||
{activas ? "Avisos activos" : activando ? "Activando…" : "Activar avisos"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={cerrarSesion}
|
||||
aria-label="Cerrar sesión"
|
||||
className="flex items-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<LogOut className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">Cerrar sesión</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="flex items-center gap-1 -mt-px overflow-x-auto">
|
||||
{NAV.map((item) => {
|
||||
const activa = esActiva(pathname, item.href);
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
to={item.href}
|
||||
aria-current={activa ? "page" : undefined}
|
||||
className={`flex items-center gap-1.5 whitespace-nowrap border-b-2 px-3 py-2.5 text-sm font-medium transition-colors ${
|
||||
activa
|
||||
? "border-primary text-primary"
|
||||
: "border-transparent text-muted hover:text-primary"
|
||||
}`}
|
||||
>
|
||||
<item.icon className="w-4 h-4" />
|
||||
{item.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useState } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
|
||||
export function CopiarDato({ etiqueta, valor }: { etiqueta: string; valor: string }) {
|
||||
const [copiado, setCopiado] = useState(false);
|
||||
|
||||
const copiar = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(valor.replace(/\s+/g, ""));
|
||||
setCopiado(true);
|
||||
setTimeout(() => setCopiado(false), 1800);
|
||||
} catch {
|
||||
// Sin permiso de portapapeles el dato sigue visible y seleccionable.
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="py-2.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-xs text-muted">{etiqueta}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={copiar}
|
||||
aria-label={`Copiar ${etiqueta}`}
|
||||
className={`shrink-0 inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium transition-colors ${
|
||||
copiado
|
||||
? "border-green-200 bg-green-50 text-green-700"
|
||||
: "border-border text-foreground hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{copiado ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
|
||||
{copiado ? "Copiado" : "Copiar"}
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-0.5 font-medium tabular-nums tracking-wide select-all [overflow-wrap:anywhere]">
|
||||
{valor}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { ChevronRight } from "lucide-react";
|
||||
import { formatCurrency, formatDate } from "@/lib/calculators";
|
||||
import { EstadoBadge } from "@/components/EstadoBadge";
|
||||
|
||||
export type MontosCotizacion = { unico: number; mensual: number };
|
||||
|
||||
function Montos({ montos }: { montos: MontosCotizacion }) {
|
||||
return (
|
||||
<>
|
||||
{montos.unico > 0 && <span className="font-semibold">{formatCurrency(montos.unico)}</span>}
|
||||
{montos.unico > 0 && montos.mensual > 0 && <span className="text-muted"> + </span>}
|
||||
{montos.mensual > 0 && (
|
||||
<span className={montos.unico > 0 ? "text-muted" : "font-semibold"}>
|
||||
{formatCurrency(montos.mensual)}/mes
|
||||
</span>
|
||||
)}
|
||||
{montos.unico === 0 && montos.mensual === 0 && <span className="text-muted">—</span>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function FilaCotizacion({
|
||||
id,
|
||||
numero,
|
||||
proyecto,
|
||||
fecha,
|
||||
estado,
|
||||
montos,
|
||||
opciones,
|
||||
}: {
|
||||
id: string;
|
||||
numero: string;
|
||||
proyecto: string;
|
||||
fecha: Date | string;
|
||||
estado: string;
|
||||
montos: MontosCotizacion;
|
||||
opciones?: Array<{ clave: string; montos: MontosCotizacion }>;
|
||||
}) {
|
||||
const fechaDate = typeof fecha === "string" ? new Date(fecha) : fecha;
|
||||
return (
|
||||
<li>
|
||||
<Link
|
||||
to={`/cliente/cotizaciones/${id}`}
|
||||
className="group flex items-center gap-4 px-5 py-4 transition-colors hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium text-primary">{numero}</span>
|
||||
<EstadoBadge estado={estado} />
|
||||
{opciones && (
|
||||
<span className="rounded-full bg-primary-light px-2 py-0.5 text-[11px] font-semibold text-primary">
|
||||
Doble propuesta
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-0.5 text-sm text-muted sm:truncate">
|
||||
{proyecto} · {formatDate(fechaDate)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-sm tabular-nums sm:text-right">
|
||||
{opciones ? (
|
||||
opciones.map((o) => (
|
||||
<p key={o.clave}>
|
||||
<span className="text-muted">Opción {o.clave}: </span>
|
||||
<Montos montos={o.montos} />
|
||||
</p>
|
||||
))
|
||||
) : (
|
||||
<p>
|
||||
<Montos montos={montos} />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 shrink-0 text-muted transition-transform group-hover:translate-x-0.5" />
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useState } from "react";
|
||||
import { Loader2, Upload } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/DialogProvider";
|
||||
|
||||
export function SubirComprobante({
|
||||
pagoId,
|
||||
variante = "secundario",
|
||||
onUploaded,
|
||||
}: {
|
||||
pagoId: string;
|
||||
variante?: "primario" | "secundario";
|
||||
onUploaded?: () => void;
|
||||
}) {
|
||||
const toast = useToast();
|
||||
const [subiendo, setSubiendo] = useState(false);
|
||||
|
||||
const onChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setSubiendo(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch(`/api/cliente/pagos/${pagoId}/comprobante`, {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
toast(data.error || "No se pudo subir el comprobante", "error");
|
||||
} else {
|
||||
toast("Comprobante enviado. Espera la revisión del administrador.", "success");
|
||||
onUploaded?.();
|
||||
}
|
||||
} catch {
|
||||
toast("Error de conexión al subir el comprobante", "error");
|
||||
} finally {
|
||||
setSubiendo(false);
|
||||
e.target.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<label
|
||||
className={`inline-flex shrink-0 items-center justify-center gap-1.5 rounded-lg px-3.5 py-2 text-sm font-medium transition-colors ${
|
||||
variante === "primario"
|
||||
? "bg-primary-light/70 text-primary-dark hover:bg-primary hover:text-white"
|
||||
: "border border-border hover:bg-gray-50"
|
||||
} ${subiendo ? "opacity-60 cursor-wait" : "cursor-pointer"}`}
|
||||
>
|
||||
{subiendo ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Upload className="w-4 h-4" />
|
||||
)}
|
||||
{subiendo ? "Subiendo…" : "Subir comprobante"}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,application/pdf"
|
||||
className="sr-only"
|
||||
onChange={onChange}
|
||||
disabled={subiendo}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user