informe-comercial-alfa/app/renovaciones/prevision/page.js

223 lines
10 KiB
JavaScript
Raw Normal View History

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 <LoginPrompt />;
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 <ErrorNotice error={error} />;
}
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 (
<div style={{ padding: 24 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
<h2>Previsión de Renovaciones</h2>
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
</div>
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
{atrasadas.length > 0 && (
<a href={linkFor(ATRASADAS)}>
<button className={win === ATRASADAS ? "on" : ""} type="button">⚠ Atrasadas ({atrasadas.length})</button>
</a>
)}
{futuros.map((m) => (
<a key={m} href={linkFor(m)}>
<button className={win === m ? "on" : ""} type="button">{MESLBL_CAP[m.slice(5, 7)] || m}</button>
</a>
))}
</div>
<div className="kpis">
<div className="kpi"><span className="n">{p.length}</span><span className="l">Renovaciones que vencen en {winLbl}</span></div>
<div className="kpi"><span className="n">{money(est)}</span><span className="l">MRR en juego</span></div>
<div className="kpi"><span className="n">{money(fc)}</span><span className="l">Forecast ponderado</span></div>
<div className="kpi">
<span className={`n ${cob != null && cob < 100 ? "pierde" : ""}`}>{cob == null ? "n/d" : `${cob}%`}</span>
<span className="l">vs. promedio renovado últimos 3 meses ({money(histProm)})</span>
</div>
<div className="kpi"><span className="n pierde">{estanc.length}</span><span className="l">En riesgo (estancadas)</span></div>
</div>
<div className={`callout ${cob != null && cob < 100 ? "warn" : "info"}`}>
{win === ATRASADAS ? (
<><b>Estas {p.length} renovaciones ya pasaron su fecha estimada y siguen abiertas.</b> En renovación el
tiempo juega en contra de forma literal: el contrato vence igual, con o sin gestión. </>
) : (
<><b>{winLbl}: {money(est)} de MRR vence este mes</b> en {p.length} contratos, con un forecast ponderado
de {money(fc)}. </>
)}
<b>Acá no se compara contra meta</b> — 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). <b>Forecast ponderado =
Σ (MRR × peso del Plan de Cierre)</b>: A 90% · B 60% · C 30% · sin plan 10%.
</div>
{sinPlan.length > 0 && (
<div className="callout warn">
<b>{sinPlan.length} de estas {p.length} no tienen Plan de Cierre</b> ({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á <b>se cuentan
igual</b>: 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.
</div>
)}
{porMes.length > 1 && (
<div className="callout warn">
<b>Vencimientos por delante:</b> {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».
</div>
)}
{p.length > 0 && <ExecMatrix arr={p} titulo="Renovaciones por vencer, por ejecutivo" hint="Monto = MRR en juego" activeDim={mze} />}
<div className="sec-div"><span>Indicadores y detalle</span></div>
<FilterChips dimLabels={DIM_LABELS} />
{pWin.length === 0 ? (
<p>No hay renovaciones en esta ventana.</p>
) : (
<div className="split23">
<div className="split23-ind">
<Panel
title="Por momento de la renovación"
hint="Ya vencido vs. próximo a vencer"
rows={agg(p, "tipo", (o) => o.est)}
cls="alerta"
dimKey="tipo"
/>
<Panel
title="¿Ya se agendó algo?"
hint={`Tarea/Cita/Llamada dentro de ${winLbl}`}
rows={aggOrd(p, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
cls="alerta"
dimKey="actAgendada"
/>
<div className="panel" style={{ paddingBottom: 4 }}>
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
</div>
<Panel
title={IND_TITULOS[indActive]}
hint={IND_HINTS[indActive]}
rows={agg(p, indActive, (o) => o.est)}
top={IND_TOP[indActive]}
dimKey={indActive}
/>
</div>
<div>
<div className="panel" style={{ paddingBottom: 6 }}>
<h3>Renovaciones con vencimiento en {winLbl}</h3>
<p className="hint">Forecast = MRR × peso del plan · scroll horizontal con la columna fija · clic en el nombre abre Dynamics</p>
</div>
<TablaPipe arr={p} tipo="fc" />
</div>
</div>
)}
</div>
);
}