Compare commits

..

No commits in common. "ce95bf82dedac1baca8de1bce6d52a93da281eec" and "6dade84d37671bc403f58b75260568f678e56ecb" have entirely different histories.

7 changed files with 33 additions and 75 deletions

View file

@ -1,11 +0,0 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "informe-comercial-dev",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"port": 3000
}
]
}

View file

@ -1,8 +1,8 @@
import Link from "next/link";
import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getPipeline, getClosed, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
import { PLAN_ORDER, EJECUTIVOS_VENTA } from "../lib/derive";
import { getPipeline, getClosed } from "../lib/queries";
import { PLAN_ORDER } from "../lib/derive";
import LoginPrompt from "../components/LoginPrompt";
import ErrorNotice from "../components/ErrorNotice";
import PlanFilterSelect from "../components/PlanFilterSelect";
@ -32,13 +32,9 @@ export default async function DetallePage({ searchParams }) {
let rows;
try {
if (detSet === "pipe") {
rows = await getPipeline(session.accessToken, scope);
} else {
const { ownerIds } = await resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA);
const statecode = detSet === "ganadas" ? 1 : 2;
rows = await getClosed(session.accessToken, scope, statecode, mes, ownerIds, VENTA_TYPE_FILTER);
}
if (detSet === "pipe") rows = await getPipeline(session.accessToken, scope);
else if (detSet === "ganadas") rows = await getClosed(session.accessToken, scope, 1, mes);
else rows = await getClosed(session.accessToken, scope, 2, mes);
} catch (error) {
return <ErrorNotice error={error} />;
}

View file

@ -1,6 +1,6 @@
import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosed, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
import { getClosed, getSystemUsers } from "../lib/queries";
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
import { getMetas, getMetaGlobal } from "../lib/metas";
import LoginPrompt from "../components/LoginPrompt";
@ -32,10 +32,9 @@ export default async function GanadasPage({ searchParams }) {
let wonAll, lostAll, allUsers;
try {
const { ownerIds } = await resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA);
[wonAll, lostAll, allUsers] = await Promise.all([
getClosed(session.accessToken, scope, 1, mes, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 1, mes),
getClosed(session.accessToken, scope, 2, mes),
getSystemUsers(session.accessToken),
]);
} catch (error) {

View file

@ -37,14 +37,6 @@ const PIPE_TYPE_FILTER =
// aparte de Ventas, no cuenta para cumplimiento de meta (ver CLAUDE.md).
const REN_TYPE_FILTER = "(alfa_typeopportunity eq 100000001 or alfa_typeopportunity eq 100000002)";
// Ventas ganadas/perdidas: los mismos 4 tipos que cuentan para cumplimiento de meta (TIPOS_META,
// derive.js) — excluye Contrato Nuevo Vecinos (100000009, cuenta para Tubería pero no es un tipo
// de meta), renovaciones y SAC-Retención/Traslado/Otros. Se aplica a won Y a lost (mismo criterio
// que VENTA_TIPOS en herramientas/build_all_months.js del sitio HTML).
export const VENTA_TYPE_FILTER =
"(alfa_typeopportunity eq 100000000 or alfa_typeopportunity eq 100000003 or " +
"alfa_typeopportunity eq 100000004 or alfa_typeopportunity eq 100000007)";
function chunk(arr, size) {
const out = [];
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
@ -230,27 +222,16 @@ export async function getRenovPipeline(accessToken, scope) {
// Resuelve una sola vez los systemuserids del scope (o [] si no aplica) — para reusar en varias
// llamadas a getClosed sin repetir la consulta a systemusers cada vez (ej. Tendencia, 6 meses).
// roster: cuando no hay propietario seleccionado ("todos"), resuelve a los systemuserid de este
// roster de nombres en vez de dejar el filtro de owner abierto — mismo patrón que el parámetro
// roster de getActividades(). Sin roster, "todos" sigue sin filtrar (ej. Renovaciones).
export async function resolveScopeOwnerIds(scope, accessToken, roster) {
if (scope.emails?.length) {
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
return { none: false, ownerIds };
}
if (roster) {
const users = await getSystemUsers(accessToken);
const ownerIds = users.filter((u) => roster.includes(u.name)).map((u) => u.id);
return { none: false, ownerIds };
}
return { none: true, ownerIds: [] };
export async function resolveScopeOwnerIds(scope, accessToken) {
if (!scope.emails?.length) return { none: true, ownerIds: [] };
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
return { none: false, ownerIds };
}
// statecode: 1 = ganadas, 2 = perdidas. month: "YYYY-MM", filtra por el mes de cierre real.
// resolvedOwnerIds: opcional, ya resuelto vía resolveScopeOwnerIds (con o sin roster) — evita
// resolver los emails/roster en cada llamada y, si se pasa, manda sobre scope.emails (así "todos"
// con roster resuelto sí filtra). typeFilter: opcional — sin él, trae cualquier tipo (Renovaciones
// pasa REN_TYPE_FILTER, Ventas pasa VENTA_TYPE_FILTER explícito).
// resolvedOwnerIds: opcional, ya resuelto vía resolveScopeOwnerIds — evita resolver los emails en
// cada llamada. typeFilter: opcional — sin él, trae cualquier tipo (Ventas ganadas/perdidas ya
// filtran por owner de rol 'ventas' en la página; Renovaciones pasa REN_TYPE_FILTER explícito).
export async function getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, typeFilter) {
const monthStart = `${month}-01`;
const [y, m] = month.split("-").map(Number);
@ -259,11 +240,8 @@ export async function getClosed(accessToken, scope, statecode, month, resolvedOw
let filter =
`statecode eq ${statecode} and actualclosedate ge ${monthStart} and actualclosedate lt ${nextMonth}`;
if (typeFilter) filter += ` and ${typeFilter}`;
if (resolvedOwnerIds !== undefined) {
if (!resolvedOwnerIds.length) return [];
filter += ` and ${ownerOrClause(resolvedOwnerIds)}`;
} else if (scope.emails?.length) {
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
if (scope.emails?.length) {
const ownerIds = resolvedOwnerIds !== undefined ? resolvedOwnerIds : await resolveOwnerIds(scope.emails, accessToken);
if (!ownerIds.length) return [];
filter += ` and ${ownerOrClause(ownerIds)}`;
}

View file

@ -1,6 +1,6 @@
import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosed, getMotivosCierre, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
import { getClosed, getMotivosCierre, getSystemUsers } from "../lib/queries";
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
import LoginPrompt from "../components/LoginPrompt";
import OwnerControl from "../components/OwnerControl";
@ -31,9 +31,8 @@ export default async function PerdemosPage({ searchParams }) {
let lostAll, allUsers;
try {
const { ownerIds } = await resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA);
[lostAll, allUsers] = await Promise.all([
getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 2, mes),
getSystemUsers(session.accessToken),
]);
const motivos = await getMotivosCierre(lostAll.map((o) => o.id), session.accessToken);

View file

@ -1,7 +1,7 @@
import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosed, getMotivosCierre, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
import { EJECUTIVOS_VENTA } from "../lib/derive";
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";
@ -28,10 +28,9 @@ export default async function ResumenPage({ searchParams }) {
let wonRaw, lost, allUsers;
try {
const { ownerIds } = await resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA);
[wonRaw, lost, allUsers] = await Promise.all([
getClosed(session.accessToken, scope, 1, mes, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER),
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);
@ -45,9 +44,9 @@ export default async function ResumenPage({ searchParams }) {
const won = wonRaw.map((o) => ({ ...o, val: o.actual }));
const sumW = won.reduce((a, o) => a + (o.val || 0), 0);
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META) — no hace falta
// re-filtrar.
const sumWMeta = sumW;
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

View file

@ -1,7 +1,7 @@
import { auth } from "../lib/auth";
import { ownerFilter } from "../lib/authz";
import { getClosed, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
import { EJECUTIVOS_VENTA, agg } from "../lib/derive";
import { getClosed, getSystemUsers, resolveScopeOwnerIds } from "../lib/queries";
import { TIPOS_META, EJECUTIVOS_VENTA, agg } from "../lib/derive";
import { getMetas, getMetaGlobal } from "../lib/metas";
import { parseFiltParam, applyFilt } from "../lib/filterState";
import LoginPrompt from "../components/LoginPrompt";
@ -102,7 +102,7 @@ export default async function TendenciaPage({ searchParams }) {
let porMes, owners, wonAll, lostAll;
try {
const [{ ownerIds }, allUsers] = await Promise.all([
resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA),
resolveScopeOwnerIds(scope, session.accessToken),
getSystemUsers(session.accessToken),
]);
owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
@ -110,8 +110,8 @@ export default async function TendenciaPage({ searchParams }) {
const crudo = await Promise.all(
meses.map(async (m) => {
const [won, lost] = await Promise.all([
getClosed(session.accessToken, scope, 1, m, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 2, m, ownerIds, VENTA_TYPE_FILTER),
getClosed(session.accessToken, scope, 1, m, ownerIds),
getClosed(session.accessToken, scope, 2, m, ownerIds),
]);
return { mes: m, won, lost };
})
@ -128,8 +128,7 @@ export default async function TendenciaPage({ searchParams }) {
const lost = applyFilt(lostRaw, filt);
const vals = won.map((o) => o.actual || 0).sort((a, b) => b - a);
const sumW = vals.reduce((a, v) => a + v, 0);
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META).
const sumWMeta = sumW;
const sumWMeta = won.filter((o) => TIPOS_META.includes(o.tipo)).reduce((a, o) => a + (o.actual || 0), 0);
const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
const denomReal = won.length + lost.length - depu;
return {
@ -181,8 +180,7 @@ export default async function TendenciaPage({ searchParams }) {
// meta: filtrar por propietario (control de arriba) sigue siendo comparable — usa su meta
// personal. Filtrar por segmento/línea/tipo no, porque nadie tiene una meta partida por producto.
const metaCmp = ["segmento", "linea", "tipo"].some((d) => filt[d]) ? null : metaDen;
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META).
const sumWMetaKpi = ing;
const sumWMetaKpi = won.filter((o) => TIPOS_META.includes(o.tipo)).reduce((a, o) => a + (o.actual || 0), 0);
const cumplKpi = metaCmp ? Math.round((sumWMetaKpi / metaCmp) * 100) : null;
const ambito = bSel ? bSel.lbl : PERIODOS.find((p) => p.k === periodo)?.lbl || "período";