import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosed, getMotivosCierre, getSystemUsers } from "../lib/queries";
import { TIPOS_META, EJECUTIVOS_VENTA } from "../lib/derive";
import { getMetas, getMetaGlobal } from "../lib/metas";
import LoginPrompt from "../components/LoginPrompt";
import OwnerControl from "../components/OwnerControl";
import ErrorNotice from "../components/ErrorNotice";
import DashBar from "../components/pipeline/DashBar";
import DashDonut from "../components/pipeline/DashDonut";
import WonTable from "../components/pipeline/WonTable";
import { money2 } from "../lib/constants";
export const dynamic = "force-dynamic";
function currentMonth() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}
export default async function ResumenPage({ searchParams }) {
const session = await auth();
if (!session?.email) return ;
const { owner } = await searchParams;
const scope = ownerFilter(session, owner);
const mes = currentMonth();
let wonRaw, lost, allUsers;
try {
[wonRaw, lost, allUsers] = await Promise.all([
getClosed(session.accessToken, scope, 1, mes),
getClosed(session.accessToken, scope, 2, mes),
getSystemUsers(session.accessToken),
]);
const motivos = await getMotivosCierre(lost.map((o) => o.id), session.accessToken);
lost = lost.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar" }));
} catch (error) {
return ;
}
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
// val en vez de actual, para que DashBar/DashDonut/WonTable (compartidos con Nuevas Oportunidades)
// no necesiten dos convenciones de nombre de campo distintas.
const won = wonRaw.map((o) => ({ ...o, val: o.actual }));
const sumW = won.reduce((a, o) => a + (o.val || 0), 0);
const sumWMeta = won
.filter((o) => TIPOS_META.includes(o.tipo))
.reduce((a, o) => a + (o.val || 0), 0);
const arpu = won.length ? sumW / won.length : 0;
// Tasa de Ganancia Total (todo el denominador) vs. Real (excluye depuración de datos, que no es
// pérdida de negocio real) — ver CLAUDE.md, lección "el forecast ponderado sobreestima" /
// hallazgo Win Rate. Replicado de pages/resumen.js del sitio HTML.
const depuN = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
const lostRealN = lost.length - depuN;
const convTotal = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
const convReal = won.length + lostRealN ? Math.round((won.length / (won.length + lostRealN)) * 100) : 0;
const metas = getMetas();
const selectedEmails = scope.locked ? [session.email] : scope.emails;
// Un solo propietario → su meta individual · varios → la suma de las suyas · ninguno (todos) →
// la meta global del equipo.
const metaDen =
selectedEmails.length === 1
? metas[selectedEmails[0].toLowerCase()] || null
: selectedEmails.length > 1
? selectedEmails.reduce((s, e) => s + (metas[e.toLowerCase()] || 0), 0) || null
: getMetaGlobal();
const cumpl = metaDen ? Math.round((sumWMeta / metaDen) * 100) : null;
return (
Resumen — {mes}
{money2(sumW)}
Ingresos Reales (ganadas)
{won.length}
Oportunidades ganadas
{money2(arpu)}
ARPU logradas
{lost.length}
Oportunidades perdidas
{convTotal}%
Tasa de Ganancia Total
{convReal}%
Tasa de Ganancia Real
{cumpl != null ? cumpl + "%" : "n/d"}
Cumplimiento de meta{metaDen ? ` (${money2(metaDen)})` : " (sin meta asignada)"}
Cumplimiento de meta cuenta solo Venta - Cliente Nuevo, Up-Selling, Cross-Selling y Plan de Cuenta (se
excluyen renovaciones y SAC).
);
}