import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getCohorte, getMotivosCierre, getSystemUsers } from "../lib/queries";
import { agg, EJECUTIVOS_VENTA } 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 FilterChips from "../components/FilterChips";
import CohMatriz from "../components/nuevas/CohMatriz";
import MesesControl from "../components/nuevas/MesesControl";
import FilterableRow from "../components/FilterableRow";
import { DYN, money, money2 } from "../lib/constants";
import { parseFiltParam, applyFilt } from "../lib/filterState";
export const dynamic = "force-dynamic";
const COH_DIMS = [
{ k: "owner", lbl: "Ejecutivo" },
{ k: "origen", lbl: "Origen" },
{ k: "tipo", lbl: "Tipo de oportunidad" },
{ k: "linea", lbl: "Línea de negocio" },
{ k: "campaign", lbl: "Campaña" },
];
const COH_METRICAS = [
{ k: "pct", lbl: "% Ganada", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Ganada").length / a.length) * 100) : null) },
{ k: "pctP", lbl: "% Perdida", rgb: "178,58,46", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Perdida").length / a.length) * 100) : null) },
{ k: "n", lbl: "Creadas", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}`), calc: (a) => a.length || null },
{ k: "mrr", lbl: "MRR ganado", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : money(v)), calc: (a) => { const s = a.filter((o) => o.estado === "Ganada").reduce((x, o) => x + o.val, 0); return a.length ? s : null; } },
];
const DIM_LABELS = { owner: "Ejecutivo", origen: "Origen", tipo: "Tipo", linea: "Línea", campaign: "Campaña", mesCohorte: "Mes de creación", motivo: "Motivo de cierre", competidor: "Competidor" };
const MESLBL = {
"01": "Ene", "02": "Feb", "03": "Mar", "04": "Abr", "05": "May", "06": "Jun",
"07": "Jul", "08": "Ago", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dic",
};
const mesLbl = (m) => (m ? `${MESLBL[m.slice(5, 7)] || m.slice(5, 7)} ${m.slice(0, 4)}` : "—");
const COH_TIPOS = {
venta: { lbl: "Venta y expansión", tipos: ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling", "Plan de Cuenta"] },
renov: { lbl: "Renovaciones", tipos: ["Contrato vencido", "Próximo a Vencer en 30/60/90"] },
todas: { lbl: "Todas", tipos: null },
};
const ESTADOS = [
{ k: "Ganada", color: "#2e8b57" },
{ k: "Perdida", color: "var(--pierde)" },
{ k: "Abierta", color: "#1e71b8" },
];
function BarraCohorte({ mes, rows }) {
const tot = rows.length || 1;
return (
{mesLbl(mes)}
{ESTADOS.map(({ k, color }) => {
const n = rows.filter((o) => o.estado === k).length;
if (!n) return null;
const pct = (n / tot) * 100;
return (
{pct > 11 ? `${n} (${Math.round(pct)}%)` : ""}
);
})}
{rows.length}
);
}
export default async function NuevasPage({ searchParams }) {
const session = await auth();
if (!session?.email) return ;
const sp = await searchParams;
const { owner, tipos: tiposParam } = sp;
const mesesSel = typeof sp.meses === "string" && sp.meses ? sp.meses.split(",") : null;
const scope = ownerFilter(session, owner);
const cohTipos = COH_TIPOS[tiposParam] ? tiposParam : "venta";
const filt = parseFiltParam(sp.f);
const cohd = COH_DIMS.some((d) => d.k === sp.cohd) ? sp.cohd : "owner";
const cohm = COH_METRICAS.some((m) => m.k === sp.cohm) ? sp.cohm : "pct";
let arrAll, allUsers;
try {
[arrAll, allUsers] = await Promise.all([
getCohorte(session.accessToken, scope),
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
]);
} catch (error) {
return ;
}
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
const tiposFiltro = COH_TIPOS[cohTipos].tipos;
const arrTipo = tiposFiltro ? arrAll.filter((o) => tiposFiltro.includes(o.tipo)) : arrAll;
const mesesDisp = [...new Set(arrTipo.map((o) => o.mesCohorte).filter(Boolean))].sort();
const mesesActivos = mesesSel ? mesesDisp.filter((m) => mesesSel.includes(m)) : mesesDisp;
const mesesEfectivos = mesesActivos.length ? mesesActivos : mesesDisp;
const arrMes = arrTipo.filter((o) => mesesEfectivos.includes(o.mesCohorte));
// Motivo y competidor de cierre solo existen para las perdidas (opportunityclose).
let arrEnr = arrMes;
try {
const perdidasIds = arrMes.filter((o) => o.estado === "Perdida").map((o) => o.id);
const motivos = await getMotivosCierre(perdidasIds, session.accessToken);
arrEnr = arrMes.map((o) =>
o.estado === "Perdida"
? { ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor || "Sin registrar" }
: o
);
} catch (error) {
return ;
}
const arr = applyFilt(arrEnr, filt);
const linkFor = (t) => {
const params = new URLSearchParams();
if (owner) params.set("owner", owner);
if (sp.meses) params.set("meses", sp.meses);
params.set("tipos", t);
return `/nuevas?${params.toString()}`;
};
const meses = [...new Set(arr.map((o) => o.mesCohorte).filter(Boolean))].sort();
const g = arr.filter((o) => o.estado === "Ganada");
const p = arr.filter((o) => o.estado === "Perdida");
const ab = arr.filter((o) => o.estado === "Abierta");
const cerr = g.length + p.length;
const pct = (x) => (arr.length ? Math.round((x / arr.length) * 100) : 0);
const mrrG = g.reduce((a, o) => a + o.val, 0);
const cohAgg = (key) => agg(arr, key, (o) => (o.estado === "Ganada" ? o.val : 0));
const cerradas = arr.filter((o) => o.diasACierre != null);
const tramos = [
{ lbl: "Mismo día", max: 0 }, { lbl: "1 a 7 días", max: 7 }, { lbl: "8 a 30 días", max: 30 },
{ lbl: "31 a 90 días", max: 90 }, { lbl: "Más de 90 días", max: Infinity },
];
let prev = -1;
const latRows = tramos.map((t) => {
const n = cerradas.filter((o) => o.diasACierre > prev && o.diasACierre <= t.max).length;
prev = t.max;
return { k: t.lbl, n };
});
const maxLat = Math.max(...latRows.map((r) => r.n), 1);
const medianaDias = (() => {
const a = cerradas.map((o) => o.diasACierre).sort((x, y) => x - y);
return a.length ? a[Math.floor(a.length / 2)] : 0;
})();
const viejas = arr.filter((o) => o.diasAbierta != null && o.diasAbierta > 90);
const detalle = [...arr].sort((a, b) => (b.estado === "Ganada" ? b.val : b.est) - (a.estado === "Ganada" ? a.val : a.est)).slice(0, 300);
return (
Cohorte de Oportunidades
({ k: m, lbl: mesLbl(m) }))} seleccion={mesesEfectivos} />
{Object.entries(COH_TIPOS).map(([k, v]) => (
{v.lbl}
))}
{arr.length === 0 ? (
No hay oportunidades creadas en el período y alcance seleccionados.
) : (
<>
{arr.length} Oportunidades creadas (cohorte)
{g.length} Hoy Ganadas · {pct(g.length)}%
{p.length} Hoy Perdidas · {pct(p.length)}%
{ab.length} Todavía Abiertas · {pct(ab.length)}%
{cerr ? `${Math.round((g.length / cerr) * 100)}%` : "n/d"} Efectividad (gana ÷ resueltas)
{money(mrrG)} MRR ganado por esta cohorte
Está página analiza el "Cohorte" , es decir el comportamiento de las oportunidades según su{" "}
"Fecha de Creación" . Ayuda a entender que pasó con las oportunidades que se crearon cada mes.
De las {arr.length} oportunidades creadas en los últimos 6 meses, hoy {g.length} están ganadas, {p.length}{" "}
perdidas y {ab.length} siguen abiertas. Las cohortes recientes tienen más abiertas solo porque son
jóvenes — mirá "% resuelto" y la latencia antes de comparar. Plan de Cuenta y los leads de
formularios/bots convierten poco por diseño (los genera telemarketing en volumen); el error a
buscar ahí es lentitud para calificar, no baja conversión.
Desenlace por cohorte de creación (estado de hoy)
Cada barra es el 100% de lo creado ese mes
{meses.map((m) =>
o.mesCohorte === m)} />)}
Latencia de decisión
Días entre crear y cerrar, de las {cerradas.length} ya resueltas
{latRows.map((r) => (
{r.k}
{r.n}
{cerradas.length ? Math.round((r.n / cerradas.length) * 100) : 0}%
))}
Mediana: {medianaDias} días para resolver.
{viejas.length > 0 && (
<> Y hay {viejas.length} todavía abiertas con más de 90 días de vida ({money(viejas.reduce((a, o) => a + o.est, 0))} estimado).>
)}
o.est)} top={8} dimKey="motivo" />
o.competidor && o.competidor !== "Ninguno"), "competidor", (o) => o.est)} top={8} dimKey="competidor" />
Cohortes en números
Cohorte Creadas Ganadas % Gana
Perdidas % Pierde Abiertas
% Resuelto MRR ganado Edad prom.
{meses.map((m) => {
const c = arr.filter((o) => o.mesCohorte === m);
const cg = c.filter((o) => o.estado === "Ganada"), cp = c.filter((o) => o.estado === "Perdida"), ca = c.filter((o) => o.estado === "Abierta");
const cpct = (x) => (c.length ? `${Math.round((x / c.length) * 100)}%` : "—");
const cerrC = cg.length + cp.length;
const edad = c.length ? Math.round(c.reduce((s, o) => s + (o.diasACierre ?? o.diasAbierta ?? 0), 0) / c.length) : 0;
return (
{mesLbl(m)}
{c.length}
{cg.length}
{cpct(cg.length)}
{cp.length}
{cpct(cp.length)}
{ca.length}
{c.length ? `${Math.round((cerrC / c.length) * 100)}%` : "—"}
{money(cg.reduce((s, o) => s + o.val, 0))}
{edad} d
);
})}
Detalle de la cohorte
Las 300 de mayor monto
Cliente / Oportunidad Estado Ejecutivo Tipo Origen
MRR Creada Días
{detalle.map((o) => (
{o.name}
{o.cliente || "—"}
{o.estado}
{o.owner}
{o.tipo || "—"}
{o.origen || "—"}
{money2(o.estado === "Ganada" ? o.val : o.est)}
{o.creada || "—"}
{o.diasACierre != null ? o.diasACierre : o.diasAbierta != null ? `${o.diasAbierta}…` : "—"}
))}
>
)}
);
}