diff --git a/app/detalle/page.js b/app/detalle/page.js index 4acb85e..8b01879 100644 --- a/app/detalle/page.js +++ b/app/detalle/page.js @@ -1,8 +1,8 @@ import Link from "next/link"; import { auth } from "../lib/auth"; import { ownerFilter } from "../lib/authz"; -import { getPipeline, getClosed } from "../lib/queries"; -import { PLAN_ORDER } from "../lib/derive"; +import { getPipeline, getClosed, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries"; +import { PLAN_ORDER, EJECUTIVOS_VENTA } from "../lib/derive"; import LoginPrompt from "../components/LoginPrompt"; import ErrorNotice from "../components/ErrorNotice"; import PlanFilterSelect from "../components/PlanFilterSelect"; @@ -32,9 +32,13 @@ export default async function DetallePage({ searchParams }) { let rows; try { - 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); + 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); + } } catch (error) { return ; } diff --git a/app/ganadas/page.js b/app/ganadas/page.js index a71e8d5..5bc0b7c 100644 --- a/app/ganadas/page.js +++ b/app/ganadas/page.js @@ -1,6 +1,6 @@ import { auth } from "../lib/auth"; import { ownerFilter } from "../lib/authz"; -import { getClosed, getSystemUsers } from "../lib/queries"; +import { getClosed, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries"; import { agg, EJECUTIVOS_VENTA } from "../lib/derive"; import { getMetas, getMetaGlobal } from "../lib/metas"; import LoginPrompt from "../components/LoginPrompt"; @@ -32,9 +32,10 @@ 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), - getClosed(session.accessToken, scope, 2, mes), + getClosed(session.accessToken, scope, 1, mes, ownerIds, VENTA_TYPE_FILTER), + getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER), getSystemUsers(session.accessToken), ]); } catch (error) { diff --git a/app/lib/queries.js b/app/lib/queries.js index a0743f9..8995045 100644 --- a/app/lib/queries.js +++ b/app/lib/queries.js @@ -37,6 +37,14 @@ 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)); @@ -222,16 +230,27 @@ 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). -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 }; +// 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: [] }; } // statecode: 1 = ganadas, 2 = perdidas. month: "YYYY-MM", filtra por el mes de cierre real. -// 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). +// 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). export async function getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, typeFilter) { const monthStart = `${month}-01`; const [y, m] = month.split("-").map(Number); @@ -240,8 +259,11 @@ 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 (scope.emails?.length) { - const ownerIds = resolvedOwnerIds !== undefined ? resolvedOwnerIds : await resolveOwnerIds(scope.emails, accessToken); + if (resolvedOwnerIds !== undefined) { + if (!resolvedOwnerIds.length) return []; + filter += ` and ${ownerOrClause(resolvedOwnerIds)}`; + } else if (scope.emails?.length) { + const ownerIds = await resolveOwnerIds(scope.emails, accessToken); if (!ownerIds.length) return []; filter += ` and ${ownerOrClause(ownerIds)}`; } diff --git a/app/perdemos/page.js b/app/perdemos/page.js index c092c53..6f64905 100644 --- a/app/perdemos/page.js +++ b/app/perdemos/page.js @@ -1,6 +1,6 @@ import { auth } from "../lib/auth"; import { ownerFilter } from "../lib/authz"; -import { getClosed, getMotivosCierre, getSystemUsers } from "../lib/queries"; +import { getClosed, getMotivosCierre, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries"; import { agg, EJECUTIVOS_VENTA } from "../lib/derive"; import LoginPrompt from "../components/LoginPrompt"; import OwnerControl from "../components/OwnerControl"; @@ -31,8 +31,9 @@ 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), + getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER), getSystemUsers(session.accessToken), ]); const motivos = await getMotivosCierre(lostAll.map((o) => o.id), session.accessToken); diff --git a/app/resumen/page.js b/app/resumen/page.js index 8f17660..8744c2e 100644 --- a/app/resumen/page.js +++ b/app/resumen/page.js @@ -1,7 +1,7 @@ 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 { getClosed, getMotivosCierre, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries"; +import { EJECUTIVOS_VENTA } from "../lib/derive"; import { getMetas, getMetaGlobal } from "../lib/metas"; import LoginPrompt from "../components/LoginPrompt"; import OwnerControl from "../components/OwnerControl"; @@ -28,9 +28,10 @@ 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), - getClosed(session.accessToken, scope, 2, mes), + getClosed(session.accessToken, scope, 1, mes, ownerIds, VENTA_TYPE_FILTER), + getClosed(session.accessToken, scope, 2, mes, ownerIds, VENTA_TYPE_FILTER), getSystemUsers(session.accessToken), ]); const motivos = await getMotivosCierre(lost.map((o) => o.id), session.accessToken); @@ -44,9 +45,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); - const sumWMeta = won - .filter((o) => TIPOS_META.includes(o.tipo)) - .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 arpu = won.length ? sumW / won.length : 0; // Tasa de Ganancia Total (todo el denominador) vs. Real (excluye depuración de datos, que no es diff --git a/app/tendencia/page.js b/app/tendencia/page.js index 3f94eef..f0f2ac4 100644 --- a/app/tendencia/page.js +++ b/app/tendencia/page.js @@ -1,7 +1,7 @@ import { auth } from "../lib/auth"; import { ownerFilter } from "../lib/authz"; -import { getClosed, getSystemUsers, resolveScopeOwnerIds } from "../lib/queries"; -import { TIPOS_META, EJECUTIVOS_VENTA, agg } from "../lib/derive"; +import { getClosed, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries"; +import { 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), + resolveScopeOwnerIds(scope, session.accessToken, EJECUTIVOS_VENTA), 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), - getClosed(session.accessToken, scope, 2, m, ownerIds), + getClosed(session.accessToken, scope, 1, m, ownerIds, VENTA_TYPE_FILTER), + getClosed(session.accessToken, scope, 2, m, ownerIds, VENTA_TYPE_FILTER), ]); return { mes: m, won, lost }; }) @@ -128,7 +128,8 @@ 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); - const sumWMeta = won.filter((o) => TIPOS_META.includes(o.tipo)).reduce((a, o) => a + (o.actual || 0), 0); + // won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META). + const sumWMeta = sumW; const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length; const denomReal = won.length + lost.length - depu; return { @@ -180,7 +181,8 @@ 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; - const sumWMetaKpi = won.filter((o) => TIPOS_META.includes(o.tipo)).reduce((a, o) => a + (o.actual || 0), 0); + // won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META). + const sumWMetaKpi = ing; const cumplKpi = metaCmp ? Math.round((sumWMetaKpi / metaCmp) * 100) : null; const ambito = bSel ? bSel.lbl : PERIODOS.find((p) => p.k === periodo)?.lbl || "período";