informe-comercial-alfa/app/perdemos/page.js

156 lines
6.2 KiB
JavaScript

import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosedRange, getMotivosCierre, getSystemUsers, VENTA_TYPE_FILTER } from "../lib/queries";
import { agg, PROPIETARIOS_VENTA } from "../lib/derive";
import { PERIODOS, periodoActivo, rangoDePeriodo } from "../lib/periodos";
import LoginPrompt from "../components/LoginPrompt";
import OwnerControl from "../components/OwnerControl";
import ErrorNotice from "../components/ErrorNotice";
import SegTabs from "../components/SegTabs";
import Panel from "../components/pipeline/Panel";
import FilterChips from "../components/FilterChips";
import { DYN, money, money2 } from "../lib/constants";
import { parseFiltParam, applyFilt } from "../lib/filterState";
export const dynamic = "force-dynamic";
const DIM_LABELS = { motivo: "Motivo", competidor: "Competidor", servicio: "Servicio", origen: "Origen", owner: "Ejecutivo" };
export default async function PerdemosPage({ searchParams }) {
const session = await auth();
if (!session?.email) return <LoginPrompt />;
const sp = await searchParams;
const { owner } = sp;
const scope = ownerFilter(session, owner);
const periodo = periodoActivo(sp.periodo);
const { from, to, lbl: periodoLbl } = rangoDePeriodo(periodo);
const filt = parseFiltParam(sp.f);
let lostAll, allUsers;
try {
[lostAll, allUsers] = await Promise.all([
getClosedRange(session.accessToken, scope, 2, from, to, undefined, VENTA_TYPE_FILTER),
getSystemUsers(session.accessToken),
]);
const motivos = await getMotivosCierre(lostAll.map((o) => o.id), session.accessToken);
lostAll = lostAll.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor }));
} catch (error) {
return <ErrorNotice error={error} />;
}
const owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
const lost = applyFilt(lostAll, filt);
const mrrPerdido = lost.reduce((a, o) => a + (o.est || 0), 0);
const clientesNuevos = lost.filter((o) => o.segmento === "Clientes Nuevos").length;
const carteraActiva = lost.filter((o) => o.segmento === "Cartera Activa").length;
return (
<div style={{ padding: 24 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
<h2>Por qué Perdemos</h2>
<OwnerControl
owners={owners}
current={scope.locked ? [session.email] : scope.emails}
locked={scope.locked}
lockedLabel={session.email}
/>
</div>
<div style={{ marginBottom: 12 }}>
<SegTabs tabs={PERIODOS} activeKey={periodo} paramName="periodo" />
</div>
<div className="kpis">
<div className="kpi">
<span className="n pierde">{lost.length}</span>
<span className="l">Oportunidades perdidas</span>
</div>
<div className="kpi">
<span className="n pierde">{money(mrrPerdido)}</span>
<span className="l">MRR estimado perdido</span>
</div>
<div className="kpi">
<span className="n">{clientesNuevos}</span>
<span className="l">Clientes Nuevos</span>
</div>
<div className="kpi">
<span className="n">{carteraActiva}</span>
<span className="l">Cartera Activa</span>
</div>
</div>
<p className="hint">
Mostrando {periodoLbl}. Sin seguimiento en el CRM no significa sin seguimiento: WhatsApp no está en Dynamics.
</p>
<FilterChips dimLabels={DIM_LABELS} />
<div className="grid2">
<Panel
title="Motivo de cierre"
hint='Fuente: Cierre de oportunidad en Dynamics · "Sin registrar" = ningún motivo (Alfa ni estándar) quedó guardado'
rows={agg(lost, "motivo", (o) => o.est)}
cls="pierde"
dimKey="motivo"
/>
<Panel
title="Competidor"
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Ninguno"), "competidor", (o) => o.est)}
cls="pierde"
dimKey="competidor"
/>
<Panel title="Servicio / Producto" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" dimKey="servicio" />
<Panel title="Origen de la oportunidad" rows={agg(lost, "origen", (o) => o.est)} cls="pierde" dimKey="origen" />
<Panel title="Perdidas por ejecutivo" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" dimKey="owner" />
</div>
<div className="panel" style={{ paddingBottom: 6 }}>
<h3>Detalle de oportunidades perdidas</h3>
</div>
{lost.length === 0 ? (
<p>No hay oportunidades 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>Seg.</th>
<th>Motivo de cierre</th>
<th>Línea de Negocio</th>
<th>Competidor</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>
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
</span>
</td>
<td>{o.motivo}</td>
<td>{o.linea || "—"}</td>
<td>{o.competidor || "—"}</td>
{!scope.locked && <td>{o.owner}</td>}
<td className="num">{o.est ? money2(o.est) : "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}