import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosedRange, getSystemUsers, VENTA_TYPE_FILTER } from "../lib/queries";
import { agg, EJECUTIVOS_VENTA, PROPIETARIOS_VENTA } from "../lib/derive";
import { PERIODOS, periodoActivo, rangoDePeriodo } from "../lib/periodos";
import { getMetas, getMetaGlobal } from "../lib/metas";
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 = { tipo: "Tipo", linea: "Línea", origen: "Origen", campaign: "Campaña" };
export default async function GanadasPage({ searchParams }) {
const session = await auth();
if (!session?.email) return ;
const sp = await searchParams;
const { owner } = sp;
const scope = ownerFilter(session, owner);
const periodo = periodoActivo(sp.periodo);
const { from, to, lbl: periodoLbl, mensual } = rangoDePeriodo(periodo);
const filt = parseFiltParam(sp.f);
let wonAll, lostAll, allUsers;
try {
[wonAll, lostAll, allUsers] = await Promise.all([
getClosedRange(session.accessToken, scope, 1, from, to, undefined, VENTA_TYPE_FILTER),
getClosedRange(session.accessToken, scope, 2, from, to, undefined, VENTA_TYPE_FILTER),
getSystemUsers(session.accessToken),
]);
} catch (error) {
return ;
}
const owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
const won = applyFilt(wonAll, filt);
const lost = applyFilt(lostAll, filt);
const metas = getMetas();
const metaGlobal = getMetaGlobal();
const sumW = won.reduce((a, o) => a + (o.actual || 0), 0);
const arpu = won.length ? sumW / won.length : 0;
const conv = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
// Cumplimiento compara contra meta MENSUAL — solo tiene sentido en "este mes"/"mes anterior".
const cumplGlobal = mensual && metaGlobal ? Math.round((sumW / metaGlobal) * 100) : null;
const porEjecutivo = EJECUTIVOS_VENTA.map((nombre) => {
const w = won.filter((o) => o.owner === nombre);
const logrado = w.reduce((a, o) => a + (o.actual || 0), 0);
const email = allUsers.find((u) => u.name === nombre)?.email;
const meta = email ? metas[email] : null;
const pct = mensual && meta ? Math.round((logrado / meta) * 100) : null;
return { nombre, logrado, meta, pct };
}).sort((a, b) => (b.pct ?? -1) - (a.pct ?? -1));
return (
Ventas Ganadas
{money2(sumW)}
Suma ingresos reales
{won.length}
Oportunidades ganadas
{money2(arpu)}
ARPU logrado
{conv}%
% Conversión
{cumplGlobal != null ? `${cumplGlobal}%` : "n/d"}
Cumplimiento equipo{!mensual ? " (n/d — meta es mensual)" : ""}
Cumplimiento de meta por ejecutivo
Ingresos reales ÷ meta mensual · verde ≥70% · ámbar 50-69% · rojo <50%
{!mensual ? " · n/d fuera de \"Este mes\"/\"Mes anterior\"" : ""}
{porEjecutivo.map((r) => (
{r.nombre}
= 70 ? "" : r.pct >= 50 ? "alerta" : "pierde"}`}
style={{ width: `${Math.min(100, r.pct ?? 0)}%` }}
/>
{r.pct == null ? "n/d" : `${r.pct}%`}
{money(r.logrado)}
{r.meta ? `/${money(r.meta)}` : ""}
))}
o.actual)} dimKey="tipo" />
o.actual)} dimKey="linea" />
o.actual)} dimKey="origen" />
o.actual)} top={7} dimKey="campaign" />
Detalle de oportunidades ganadas
{won.length === 0 ? (
No hay oportunidades ganadas en este período para este filtro.
) : (
| Cliente |
Oportunidad |
Seg. |
{!scope.locked && Ejecutivo | }
Tipo |
Línea de Negocio |
Origen |
MRR |
Cierre |
{[...won].sort((a, b) => b.actual - a.actual).map((o) => (
| {o.cliente || "—"} |
{o.name}
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
{!scope.locked && {o.owner} | }
{o.tipo} |
{o.linea} |
{o.origen} |
{money2(o.actual)} |
{o.actualClose || "—"} |
))}
)}
);
}