import { auth } from "../../lib/auth";
import { ownerFilter } from "../../lib/authz";
import { getRenovClosed, getMotivosCierre, getSystemUsers } from "../../lib/queries";
import { agg, EJECUTIVOS_RENOV, catsWonLost } 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 ComparePanelMotivo from "../../components/pipeline/ComparePanelMotivo";
import FilterChips from "../../components/FilterChips";
import { DYN, money2 } from "../../lib/constants";
import { parseFiltParam, applyFilt } from "../../lib/filterState";
export const dynamic = "force-dynamic";
const DIM_LABELS = { linea: "Línea de Negocio", motivo: "Motivo", tipo: "Momento", competidor: "Competidor", owner: "Ejecutivo", servicio: "Servicio" };
function currentMonth() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
function retencion(w, l) {
const t = w.length + l.length;
return t ? Math.round((w.length / t) * 100) : null;
}
export default async function RenovPerdidasPage({ searchParams }) {
const session = await auth();
if (!session?.email) return ;
const sp = await searchParams;
const { owner } = sp;
const scope = ownerFilter(session, owner);
const mes = currentMonth();
const filt = parseFiltParam(sp.f);
let lostRaw, wonRaw, allUsers;
try {
[lostRaw, wonRaw, allUsers] = await Promise.all([
getRenovClosed(session.accessToken, scope, 2, mes),
getRenovClosed(session.accessToken, scope, 1, mes),
getSystemUsers(session.accessToken),
]);
const motivos = await getMotivosCierre(lostRaw.map((o) => o.id), session.accessToken);
lostRaw = lostRaw.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor || o.competidor }));
} catch (error) {
return ;
}
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
const lost = applyFilt(lostRaw, filt);
const won = applyFilt(wonRaw, filt);
const sumL = lost.reduce((a, o) => a + (o.est || 0), 0);
const ret = retencion(won, lost);
const churn = ret == null ? null : 100 - ret;
const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
const conMotivo = lost.length - depu;
const catsLinea = catsWonLost(won, lost, "linea");
return (
Renovaciones Perdidas — {mes}
{lost.length}Contratos no renovados
{money2(sumL)}MRR perdido
20 ? "pierde" : ""}`}>{churn == null ? "n/d" : `${churn}%`}
Churn del período
{conMotivo}Con motivo real declarado
{money2(lost.length ? sumL / lost.length : 0)}Ticket promedio perdido
Cada contrato de esta lista es MRR que ya estaba adentro y se fue.{" "}
{depu > 0 && (
<>{depu} de {lost.length} cerraron como Envejecida/Cancelada/Agotada (depuración, no rechazo del cliente); la causa real se lee en las{" "}
{conMotivo} restantes. >
)}
Ojo: WhatsApp no está en Dynamics; un motivo vacío es «sin motivo en el CRM», no «no se gestionó».
{catsLinea.length > 0 && (
)}
o.est)} cls="pierde" dimKey="motivo" />
o.est)} cls="pierde" dimKey="tipo" />
o.competidor && o.competidor !== "Sin registrar"), "competidor", (o) => o.est)}
cls="pierde"
top={7}
dimKey="competidor"
/>
o.est)} cls="pierde" dimKey="owner" />
o.est)} cls="pierde" dimKey="linea" />
o.est)} cls="pierde" top={7} dimKey="servicio" />
Detalle de contratos no renovados
{lost.length === 0 ? (
No hay renovaciones perdidas en este período para este filtro.
) : (
| Cliente |
Oportunidad |
Motivo de cierre |
Línea de Negocio |
{!scope.locked && Ejecutivo | }
MRR est. |
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
| {o.cliente || "—"} |
{o.name} |
{o.motivo} |
{o.linea || "—"} |
{!scope.locked && {o.owner} | }
{o.est ? money2(o.est) : "—"} |
))}
)}
);
}