import { auth } from "../lib/auth"; import { ownerFilter } from "../lib/authz"; import { getPipeline, getSystemUsers, getActividades, getStageDurations, getClosed } from "../lib/queries"; import LoginPrompt from "../components/LoginPrompt"; import OwnerControl from "../components/OwnerControl"; import ErrorNotice from "../components/ErrorNotice"; import Panel from "../components/pipeline/Panel"; import MatrizCalidad from "../components/pipeline/MatrizCalidad"; import TablaPipe from "../components/pipeline/TablaPipe"; import ExecMatrix from "../components/pipeline/ExecMatrix"; import VelPanel from "../components/pipeline/VelPanel"; import SegTabs from "../components/SegTabs"; import BuscadorOportunidades from "../components/BuscadorOportunidades"; import FilterChips from "../components/FilterChips"; import ReportModal from "../components/ReportModal"; import PanelesCalidad from "../components/pipeline/PanelesCalidad"; import RepTable from "../components/pipeline/RepTable"; import { money } from "../lib/constants"; import { EJECUTIVOS_VENTA, agg, aggOrd, hayClasif, cierreVencido, decorarActividadVentana, ACTAGENDADA_ORDEN, pipeVelFor } from "../lib/derive"; import { parseFiltParam, applyFilt } from "../lib/filterState"; import { getMetas } from "../lib/metas"; function currentMonth() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; } export const dynamic = "force-dynamic"; const IND_TABS = [ { k: "tipo", lbl: "Tipo" }, { k: "origen", lbl: "Origen" }, { k: "competidor", lbl: "Competidor" }, { k: "linea", lbl: "Línea" }, { k: "servicio", lbl: "Servicio" }, { k: "vel", lbl: "Velocidad" }, ]; const IND_TITULOS = { tipo: "Por Tipo de Oportunidad", origen: "Por Origen de Oportunidad", competidor: "Por Competidor", linea: "Por Línea de Negocio", servicio: "Por Servicio / Producto", }; const IND_TOP = { tipo: undefined, origen: 7, competidor: 7, linea: undefined, servicio: 7 }; const DIM_LABELS = { tipo: "Tipo", origen: "Origen", competidor: "Competidor", linea: "Línea", servicio: "Servicio", luz: "Luz Amarilla", calidad: "Calidad", mov: "Movimiento", actAgendada: "Agendado" }; export default async function TuberiaPage({ searchParams }) { const session = await auth(); if (!session?.email) return ; const sp = await searchParams; const { owner } = sp; const scope = ownerFilter(session, owner); const filt = parseFiltParam(sp.f); const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "tipo"; const mze = sp.mze; let pipelineRows, allUsers, actividades; try { [pipelineRows, allUsers, actividades] = await Promise.all([ getPipeline(session.accessToken, scope), session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]), getActividades(session.accessToken, scope), ]); } catch (error) { return ; } const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name)); // Ventana abierta (desde hoy en adelante, sin tope): Tubería no tiene selector de período, así // que la pregunta es "¿ya se planeó algo para moverla, sea cuando sea?" (ver utils.js del HTML). const hoy = new Date().toISOString().slice(0, 10); const allRows = decorarActividadVentana(pipelineRows, actividades, hoy, "9999-12-31"); const rows = applyFilt(allRows, filt); const stageDurations = indActive === "vel" ? await getStageDurations(rows.map((o) => o.id), session.accessToken) : []; // Informe para el ejecutivo — solo disponible con un único propietario seleccionado (igual // criterio que openReporteEjecutivo() del HTML: ownerSelPipe.size===1). No depende de los // filtros de panel (`f`) activos: es un snapshot completo de la tubería de esa persona. const ownerName = scope.emails?.length === 1 ? session.isAdmin ? allUsers.find((u) => u.email === scope.emails[0])?.name : session.user?.name : null; let reportContent = null; if (ownerName) { const p = allRows.filter((o) => o.owner === ownerName); const est = p.reduce((a, o) => a + o.est, 0); const fc = p.reduce((a, o) => a + o.fc, 0); const hoyMes = currentMonth(); const meta = getMetas()[scope.emails[0]] || null; let wonMes = []; try { wonMes = await getClosed(session.accessToken, scope, 1, hoyMes); } catch { wonMes = []; } const wonSum = wonMes.reduce((a, o) => a + (o.actual || 0), 0); const fcMes = p.filter((o) => o.mesCierre === hoyMes).reduce((a, o) => a + o.fc, 0); const cobertura = meta ? Math.round(((wonSum + fcMes) / meta) * 100) : null; const actuar = p .filter((o) => (o.mesCierre && o.mesCierre < hoyMes) || (o.mesCierre === hoyMes && o.plan !== "Plan A - En firma" && o.plan !== "Plan B - En Negociación")) .sort((a, b) => b.est - a.est); const tocar = p.filter((o) => o.actividad === "Fría" || o.actividad === "Congelada").sort((a, b) => b.est - a.est); const enfocarse = p.filter((o) => (o.plan === "Plan A - En firma" || o.plan === "Plan B - En Negociación") && !o.estanc).sort((a, b) => b.fc - a.fc); reportContent = ( <>
Informe de tubería individual

{ownerName}

{p.length}Oportunidades activas
{money(est)}MRR en tubería
{money(fc)}Forecast ponderado
{meta &&
{cobertura}%Cobertura de meta ({money(meta)})
}
{p.filter((o) => o.estanc).length}Estancadas
🔴 Actuar ya ({actuar.length}) — cierre vencido, o este/próximo mes sin un plan sólido. Decidir esta semana.
🟡 Tocar — frías o congeladas ({tocar.length}) — más de 30-60 días sin avanzar o sin actividad. Reactivar o cerrar.
🟢 Enfocarse — con tracción real ({enfocarse.length}) — Plan A/B avanzando sin estancarse.
); } const sorted = [...rows].sort((a, b) => b.est - a.est); const totalEst = rows.reduce((a, r) => a + r.est, 0); const totalFc = rows.reduce((a, r) => a + r.fc, 0); const estanc = rows.filter((r) => r.estanc); const estancadas = estanc.length; const estancEst = estanc.reduce((a, r) => a + r.est, 0); const sinPlan = rows.filter((r) => r.plan === "Sin plan de cierre"); const sinPlanEst = sinPlan.reduce((a, r) => a + r.est, 0); const vencidas = rows.filter(cierreVencido); const enProponerONegociacion = rows.filter((r) => r.faseActual === "Proponer" || r.faseActual === "Negociación").length; return (

Tubería Activa

{reportContent}
{rows.length} Oportunidades activas
{money(totalEst)} Estimado total
{money(totalFc)} Forecast ponderado
{estancadas} Estancadas (>14d sin actividad o >90d en fase)
{sinPlan.length} Sin plan de cierre · {money(sinPlanEst)}
{sorted.length === 0 ? (

No hay oportunidades activas para este filtro.

) : ( <>
Estancada = más de 14 días sin actividad o más de 90 en la misma fase. Hoy hay{" "} {estancadas} de {rows.length} ({rows.length ? Math.round((estancadas / rows.length) * 100) : 0}%) por{" "} {money(estancEst)} de MRR; {vencidas.length} ya pasaron su fecha estimada de cierre y{" "} {enProponerONegociacion} están en Proponer o Negociación.
Indicadores y detalle
{hayClasif(rows) && } o.est)} cls="alerta" top={7} dimKey="luz" /> o.est)} cls="alerta" dimKey="actAgendada" />
{indActive === "vel" ? ( ) : ( o.est)} top={IND_TOP[indActive]} dimKey={indActive} /> )}

Detalle de la tubería activa

Plan: A en firma · B negociación · C seguimiento · D recalificar · Actividad: ● verde activa, ámbar tibia, naranja fría, rojo congelada · ⚠ cierre vencido

)}
); }