import { auth } from "../../lib/auth";
import { ownerFilter } from "../../lib/authz";
import { getRenovPipeline, getSystemUsers, getActividades, getStageDurations } 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 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_RENOV, agg, aggOrd, cierreVencido, decorarActividadVentana, ACTAGENDADA_ORDEN, pipeVelFor } from "../../lib/derive";
import { parseFiltParam, applyFilt } from "../../lib/filterState";
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: "owner", lbl: "Ejecutivo" },
{ k: "cliente", lbl: "Cliente" },
{ k: "linea", lbl: "Línea" },
{ k: "competidor", lbl: "Competidor" },
{ k: "vel", lbl: "Velocidad" },
];
const IND_TITULOS = {
owner: "Por Ejecutivo",
cliente: "Por Cliente",
linea: "Por Línea de Negocio",
competidor: "Por Competidor",
};
const IND_HINTS = {
owner: "Ordenado por MRR en juego",
cliente: "Las cuentas con más MRR por renovar",
linea: "Ordenado por MRR en juego",
competidor: "Contra quién se compite la renovación",
};
const IND_TOP = { owner: undefined, cliente: 7, linea: undefined, competidor: 7 };
const DIM_LABELS = { owner: "Ejecutivo", cliente: "Cliente", linea: "Línea", competidor: "Competidor", tipo: "Momento", actAgendada: "Agendado" };
export default async function RenovTuberiaPage({ 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 : "owner";
const mze = sp.mze;
let pipelineRows, allUsers, actividades;
try {
[pipelineRows, allUsers, actividades] = await Promise.all([
getRenovPipeline(session.accessToken, scope),
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
getActividades(session.accessToken, scope, EJECUTIVOS_RENOV),
]);
} catch (error) {
return ;
}
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
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) : [];
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 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 yaVencido = rows.filter((r) => r.tipo === "Contrato vencido");
const pctSinPlan = rows.length ? Math.round((sinPlan.length / rows.length) * 100) : 0;
// Informe de Renovación — solo con un único propietario seleccionado (ver mismo criterio en
// tuberia/page.js de Ventas). Usa `allRows` (sin el filtro `f` activo): es un snapshot completo.
const ownerName = scope.emails?.length === 1
? session.isAdmin
? allUsers.find((u) => u.email === scope.emails[0])?.name
: session.user?.name
: null;
let renovReportContent = 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 yaVencidoP = p.filter((o) => o.tipo === "Contrato vencido");
const hoyMes = currentMonth();
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);
renovReportContent = (
<>
Informe de renovaciones individual
{ownerName}
No cuenta para la meta comercial — el indicador es retención
{p.length}Renovaciones abiertas
{money(est)}MRR en juego
{money(fc)}Forecast ponderado
{yaVencidoP.length}Con el contrato ya vencido
{p.filter((o) => o.estanc).length}Estancadas
🔴 Actuar ya ({actuar.length}) — contrato vencido, o vence este/próximo mes sin un plan sólido.
🟡 Tocar — frías o congeladas ({tocar.length}) — más de 30-60 días sin avanzar o sin actividad.
🟢 Encaminadas — con tracción real ({enfocarse.length}) — Plan A/B, avanzando bien y sin estancarse.
>
);
}
return (
Tubería de Renovaciones
{renovReportContent}
{money(totalEst)}MRR en juego (est.)
{rows.length}Renovaciones abiertas
{money(totalFc)}Forecast ponderado
{yaVencido.length}Con el contrato YA vencido · {money(yaVencido.reduce((a, o) => a + o.est, 0))}
{estanc.length}Estancadas · {money(estancEst)}
{sinPlan.length}Sin plan de cierre · {money(sinPlanEst)}
{rows.length === 0 ? (
No hay renovaciones activas para este filtro.
) : (
<>
MRR que ya factura y hay que no perder: {money(totalEst)} en{" "}
{rows.length} renovaciones abiertas, {yaVencido.length} con el contrato ya vencido. {estanc.length} de {rows.length}{" "}
están estancadas (+14 días sin actividad o +90 en la misma fase) por {money(estancEst)}, y{" "}
{vencidas.length} pasaron su fecha estimada de cierre.
{pctSinPlan > 50 && (
{pctSinPlan}% de la tubería de renovaciones no tiene Plan de Cierre ({sinPlan.length} de{" "}
{rows.length}, {money(sinPlanEst)}). Sin plan pesan solo 10% en el forecast: {sinPlan.length} contratos que vencen no tienen fecha de firma comprometida.
)}
Indicadores y detalle
o.est)}
cls="alerta"
dimKey="tipo"
/>
o.est)}
cls="alerta"
dimKey="actAgendada"
/>
{indActive === "vel" ? (
) : (
o.est)}
top={IND_TOP[indActive]}
dimKey={indActive}
/>
)}
Detalle de la tubería de renovaciones
Plan: A en firma · B negociación
· C seguimiento · D recalificar · ⚠ cierre vencido
>
)}
);
}