import { auth } from "../../lib/auth"; import { ownerFilter } from "../../lib/authz"; import { getRenovPipeline, getRenovClosed, getSystemUsers, getActividades } from "../../lib/queries"; import { agg, aggOrd, EJECUTIVOS_RENOV, decorarActividadVentana, ACTAGENDADA_ORDEN } from "../../lib/derive"; 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 SegTabs from "../../components/SegTabs"; import FilterChips from "../../components/FilterChips"; import { money } from "../../lib/constants"; import { parseFiltParam, applyFilt } from "../../lib/filterState"; 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" }, ]; 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 este mes", 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" }; const ATRASADAS = "__ATRASADAS__"; const MESLBL_CAP = { "01": "Enero", "02": "Febrero", "03": "Marzo", "04": "Abril", "05": "Mayo", "06": "Junio", "07": "Julio", "08": "Agosto", "09": "Septiembre", "10": "Octubre", "11": "Noviembre", "12": "Diciembre", }; function currentMonth() { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; } function mesAnterior(m, n) { const [y, mm] = m.split("-").map(Number); const d = new Date(y, mm - 1 - n, 1); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`; } function ventanaDeMes(win, hoyIso) { if (win === ATRASADAS) return { ini: hoyIso, fin: "9999-12-31" }; const [y, m] = win.split("-").map(Number); const fin = new Date(y, m, 0); return { ini: `${win}-01`, fin: `${fin.getFullYear()}-${String(fin.getMonth() + 1).padStart(2, "0")}-${String(fin.getDate()).padStart(2, "0")}` }; } export default async function RenovPrevisionPage({ searchParams }) { const session = await auth(); if (!session?.email) return ; const sp = await searchParams; const { owner, w: winParam } = sp; const scope = ownerFilter(session, owner); const hoy = currentMonth(); const filt = parseFiltParam(sp.f); const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner"; const mze = sp.mze; let allRows, allUsers, historico, actividades; try { [allRows, allUsers, actividades] = await Promise.all([ getRenovPipeline(session.accessToken, scope), session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]), getActividades(session.accessToken, scope, EJECUTIVOS_RENOV), ]); // Referencia honesta: MRR realmente renovado en los 3 meses cerrados anteriores. const meses3 = [mesAnterior(hoy, 1), mesAnterior(hoy, 2), mesAnterior(hoy, 3)]; const won3 = await Promise.all(meses3.map((m) => getRenovClosed(session.accessToken, scope, 1, m))); historico = won3.map((w) => w.reduce((a, o) => a + (o.actual || 0), 0)); } catch (error) { return ; } const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name)); const histProm = historico.length ? historico.reduce((a, b) => a + b, 0) / historico.length : 0; const futuros = [...new Set(allRows.map((o) => o.mesCierre).filter((m) => m && m >= hoy))].sort(); const atrasadas = allRows.filter((o) => !o.mesCierre || o.mesCierre < hoy); const win = winParam === ATRASADAS ? ATRASADAS : futuros.includes(winParam) ? winParam : futuros[0] || hoy; const hoyIso = new Date().toISOString().slice(0, 10); const { ini, fin: finVentana } = ventanaDeMes(win, hoyIso); const pWinRaw = win === ATRASADAS ? atrasadas : allRows.filter((o) => o.mesCierre === win); const pWin = decorarActividadVentana(pWinRaw, actividades, ini, finVentana); const p = applyFilt(pWin, filt); const winLbl = win === ATRASADAS ? "renovaciones atrasadas (fecha estimada ya vencida)" : MESLBL_CAP[win.slice(5, 7)] || win; const est = p.reduce((a, o) => a + o.est, 0); const fc = p.reduce((a, o) => a + o.fc, 0); const estanc = p.filter((o) => o.estanc); const sinPlan = p.filter((o) => o.plan === "Sin plan de cierre"); const cob = histProm ? Math.round((fc / histProm) * 100) : null; const porMes = futuros.map((m) => ({ lbl: MESLBL_CAP[m.slice(5, 7)] || m, n: allRows.filter((o) => o.mesCierre === m).length, est: allRows.filter((o) => o.mesCierre === m).reduce((a, o) => a + o.est, 0), })); const linkFor = (w) => { const params = new URLSearchParams(); if (owner) params.set("owner", owner); params.set("w", w); return `/renovaciones/prevision?${params.toString()}`; }; return (

Previsión de Renovaciones

{atrasadas.length > 0 && ( )} {futuros.map((m) => ( ))}
{p.length}Renovaciones que vencen en {winLbl}
{money(est)}MRR en juego
{money(fc)}Forecast ponderado
{cob == null ? "n/d" : `${cob}%`} vs. promedio renovado últimos 3 meses ({money(histProm)})
{estanc.length}En riesgo (estancadas)
{win === ATRASADAS ? ( <>Estas {p.length} renovaciones ya pasaron su fecha estimada y siguen abiertas. En renovación el tiempo juega en contra de forma literal: el contrato vence igual, con o sin gestión. ) : ( <>{winLbl}: {money(est)} de MRR vence este mes en {p.length} contratos, con un forecast ponderado de {money(fc)}. )} Acá no se compara contra meta — la meta comercial no incluye renovaciones. La referencia útil es lo que se renovó de verdad en los 3 meses anteriores ({money(histProm)} en promedio). Forecast ponderado = Σ (MRR × peso del Plan de Cierre): A 90% · B 60% · C 30% · sin plan 10%.
{sinPlan.length > 0 && (
{sinPlan.length} de estas {p.length} no tienen Plan de Cierre ({money(sinPlan.reduce((a, o) => a + o.est, 0))}). A diferencia de Previsión de Ventas —que las excluye por no tener compromiso real— acá se cuentan igual: el contrato vence tenga plan o no, y esconderlas sería esconder el riesgo. Pesan solo 10% en el ponderado, así que el forecast las subestima a propósito.
)} {porMes.length > 1 && (
Vencimientos por delante: {porMes.map((m) => `${m.lbl} — ${money(m.est)} (${m.n})`).join(" · ")}. Empezar la gestión el mes anterior es lo que mueve la renovación de «tarde» a «a tiempo».
)} {p.length > 0 && }
Indicadores y detalle
{pWin.length === 0 ? (

No hay renovaciones en esta ventana.

) : (
o.est)} cls="alerta" dimKey="tipo" /> o.est)} cls="alerta" dimKey="actAgendada" />
o.est)} top={IND_TOP[indActive]} dimKey={indActive} />

Renovaciones con vencimiento en {winLbl}

Forecast = MRR × peso del plan · scroll horizontal con la columna fija · clic en el nombre abre Dynamics

)}
); }