151 lines
6.9 KiB
JavaScript
151 lines
6.9 KiB
JavaScript
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 <LoginPrompt />;
|
|
|
|
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 <ErrorNotice error={error} />;
|
|
}
|
|
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 (
|
|
<div style={{ padding: 24 }}>
|
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
|
<h2>Renovaciones Perdidas — {mes}</h2>
|
|
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
|
</div>
|
|
|
|
<div className="kpis">
|
|
<div className="kpi"><span className="n pierde">{lost.length}</span><span className="l">Contratos no renovados</span></div>
|
|
<div className="kpi"><span className="n pierde">{money2(sumL)}</span><span className="l">MRR perdido</span></div>
|
|
<div className="kpi">
|
|
<span className={`n ${churn != null && churn > 20 ? "pierde" : ""}`}>{churn == null ? "n/d" : `${churn}%`}</span>
|
|
<span className="l">Churn del período</span>
|
|
</div>
|
|
<div className="kpi"><span className="n">{conMotivo}</span><span className="l">Con motivo real declarado</span></div>
|
|
<div className="kpi"><span className="n">{money2(lost.length ? sumL / lost.length : 0)}</span><span className="l">Ticket promedio perdido</span></div>
|
|
</div>
|
|
|
|
<div className="callout warn">
|
|
<b>Cada contrato de esta lista es MRR que ya estaba adentro y se fue.</b>{" "}
|
|
{depu > 0 && (
|
|
<><b>{depu} de {lost.length}</b> cerraron como Envejecida/Cancelada/Agotada (depuración, no rechazo del cliente); la causa real se lee en las{" "}
|
|
{conMotivo} restantes. </>
|
|
)}
|
|
Ojo: <b>WhatsApp no está en Dynamics</b>; un motivo vacío es «sin motivo en el CRM», no «no se gestionó».
|
|
</div>
|
|
|
|
{catsLinea.length > 0 && (
|
|
<ComparePanelMotivo
|
|
title="Renovación por línea de negocio: qué se conserva y qué se va"
|
|
hint="Ganadas vs. perdidas en MRR, por línea de negocio"
|
|
cats={catsLinea}
|
|
dimKey="linea"
|
|
/>
|
|
)}
|
|
|
|
<FilterChips dimLabels={DIM_LABELS} />
|
|
<div className="grid3">
|
|
<Panel title="Motivo de cierre" hint="Fuente: Cierre de oportunidad en Dynamics" rows={agg(lost, "motivo", (o) => o.est)} cls="pierde" dimKey="motivo" />
|
|
<Panel title="Por momento de la renovación" hint="¿Se perdió antes o después de vencer el contrato?" rows={agg(lost, "tipo", (o) => o.est)} cls="pierde" dimKey="tipo" />
|
|
<Panel
|
|
title="Competidor"
|
|
hint="Contra quién se perdió"
|
|
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Sin registrar"), "competidor", (o) => o.est)}
|
|
cls="pierde"
|
|
top={7}
|
|
dimKey="competidor"
|
|
/>
|
|
<Panel title="Por Ejecutivo" hint="Ordenado por MRR perdido" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" dimKey="owner" />
|
|
<Panel title="Por Línea de Negocio" hint="Ordenado por MRR perdido" rows={agg(lost, "linea", (o) => o.est)} cls="pierde" dimKey="linea" />
|
|
<Panel title="Por Servicio / Producto" hint="Ordenado por MRR perdido" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" top={7} dimKey="servicio" />
|
|
</div>
|
|
|
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
|
<h3>Detalle de contratos no renovados</h3>
|
|
</div>
|
|
{lost.length === 0 ? (
|
|
<p>No hay renovaciones perdidas en este período para este filtro.</p>
|
|
) : (
|
|
<div className="tw">
|
|
<div className="ts">
|
|
<table>
|
|
<thead>
|
|
<tr>
|
|
<th>Cliente</th>
|
|
<th>Oportunidad</th>
|
|
<th>Motivo de cierre</th>
|
|
<th>Línea de Negocio</th>
|
|
{!scope.locked && <th>Ejecutivo</th>}
|
|
<th className="num">MRR est.</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
|
|
<tr key={o.id}>
|
|
<td>{o.cliente || "—"}</td>
|
|
<td><a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a></td>
|
|
<td>{o.motivo}</td>
|
|
<td>{o.linea || "—"}</td>
|
|
{!scope.locked && <td>{o.owner}</td>}
|
|
<td className="num">{o.est ? money2(o.est) : "—"}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|