import { dv, fv, lookupType, odataString } from "./dataverse";
import { derivePipelineRow, segmentoDe, normComp, EJECUTIVOS_VENTA, OBJETIVO_A_ETAPA } from "./derive";
const OPP_SELECT = [
"opportunityid",
"name",
"_ownerid_value",
"alfa_typeopportunity",
"alfa_tipodeventa",
"_alfa_lineadenegocioid_value",
"_alfa_servicioproductoid_value",
"estimatedvalue",
"actualvalue",
"alfa_plandecierre",
"alfa_envejecimiento",
"alfa_diassinactividad",
"estimatedclosedate",
"actualclosedate",
"stepname",
"alfa_estadodelanegociacion",
"_customerid_value",
"_campaignid_value",
"_alfa_competidorid_value",
"alfa_puntuaciondelaoportunidad",
"alfa_niveldeoportunidadestrellas",
"alfa_clasificaciondeoportunidad",
"alfa_luzamarilla",
"msdyn_forecastcategory",
].join(",");
// Tubería: 5 tipos de la cartera "en pipeline" (ver ALFA_Estructura_Oportunidades_CRM.md).
const PIPE_TYPE_FILTER =
"(alfa_typeopportunity eq 100000000 or alfa_typeopportunity eq 100000003 or " +
"alfa_typeopportunity eq 100000004 or alfa_typeopportunity eq 100000007 or alfa_typeopportunity eq 100000009)";
// Renovaciones: Contrato Vencido (100000002) y Próximo a Vencer 30/60/90 (100000001) — universo
// 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));
return out;
}
export async function getSystemUsers(accessToken) {
const data = await dv(
"systemusers?$select=systemuserid,fullname,internalemailaddress&$filter=isdisabled eq false",
accessToken
);
return (data.value || []).map((u) => ({
id: u.systemuserid,
name: u.fullname,
email: (u.internalemailaddress || "").toLowerCase(),
}));
}
export async function resolveOwnerId(email, accessToken) {
if (!email) return null;
const data = await dv(
`systemusers?$select=systemuserid&$filter=${encodeURIComponent(
`internalemailaddress eq '${odataString(email)}'`
)}`,
accessToken
);
return data.value?.[0]?.systemuserid || null;
}
function mapOpportunityRow(o) {
const tipo = fv(o, "alfa_typeopportunity");
return {
id: o.opportunityid,
name: o.name,
owner: fv(o, "_ownerid_value"),
tipo,
segmento: segmentoDe(tipo),
origen: fv(o, "alfa_tipodeventa"),
linea: fv(o, "_alfa_lineadenegocioid_value"),
servicio: fv(o, "_alfa_servicioproductoid_value"),
est: o.estimatedvalue || 0,
actual: o.actualvalue || 0,
plan: fv(o, "alfa_plandecierre"),
env: o.alfa_envejecimiento ?? null,
dsa: o.alfa_diassinactividad ?? null,
close: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null,
actualClose: o.actualclosedate ? o.actualclosedate.slice(0, 10) : null,
step: o.stepname,
estado: o.alfa_estadodelanegociacion || null,
cliente: fv(o, "_customerid_value"),
campaign: fv(o, "_campaignid_value"),
score: o.alfa_puntuaciondelaoportunidad ?? null,
estrellas: o.alfa_niveldeoportunidadestrellas ?? null,
clasif: fv(o, "alfa_clasificaciondeoportunidad") || "Sin clasificar",
luz: fv(o, "alfa_luzamarilla") || "Sin registrar",
competidor: normComp(fv(o, "_alfa_competidorid_value")),
// Escala propia de ALFA+ (NO el forecastcategory estándar de Dynamics — ver CLAUDE.md):
// la etiqueta ya trae el % adelante ("20% Calificada" … "90% Firma de contrato"), de ahí se
// deriva el orden sin mantener un mapa aparte.
prev: fv(o, "msdyn_forecastcategory") || "Sin categoría",
prevPct: parseInt(fv(o, "msdyn_forecastcategory") || "", 10) || 0,
};
}
async function getFaseActual(oppIds, accessToken) {
const fase = {};
for (const batch of chunk(oppIds, 150)) {
if (!batch.length) continue;
const conditions = batch.map((id) => `${id}`).join("");
const fetchXml =
`` +
`` +
`` +
`${conditions}` +
``;
const data = await dv(`alfa_stagedurations?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
for (const r of data.value || []) {
const oid = r["_alfa_opportunity_value"] || r.alfa_opportunity;
const started = r.alfa_started;
const subj = (r.alfa_subject || "").replace("Fase: ", "");
if (!fase[oid] || (started && started > fase[oid].started)) {
fase[oid] = { fase: subj, started };
}
}
}
return fase;
}
// Historial completo de fases COMPLETADAS por oportunidad (a diferencia de getFaseActual(), que
// solo trae la fase en curso) — para Velocidad de movimiento (pipeVelFor(), derive.js). statuscode
// eq 100000000 = "Completado" en este tenant (confirmado en herramientas/build_pipevel.js del
// sitio HTML) — excluye la fase activa, aún sin cerrar, de cada oportunidad.
export async function getStageDurations(oppIds, accessToken) {
const out = [];
for (const batch of chunk(oppIds, 150)) {
if (!batch.length) continue;
const conditions = batch.map((id) => `${id}`).join("");
const fetchXml =
`` +
`` +
`` +
`${conditions}` +
``;
const data = await dv(`alfa_stagedurations?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
for (const r of data.value || []) {
const oppId = r["_alfa_opportunity_value"] || r.alfa_opportunity;
if (!oppId || r.alfa_duration == null) continue;
const subj = (r.alfa_subject || "").replace("Fase: ", "");
if (!subj || subj === "Ganada") continue; // no es un tramo de velocidad
out.push({ oppId, fase: subj === "Proponer" ? "Negociación" : subj, dur: r.alfa_duration });
}
}
return out;
}
// Motivo/competidor de cierre — viven en opportunityclose, no en opportunity (ver
// contexto_tabla_cierre_oportunidad.md). alfa_motivodecierre es el campo principal (Alfa);
// opportunitystatuscode es el respaldo estándar — en la práctica muchos cierres recientes
// solo llenan el estándar. Nos quedamos con el cierre más reciente por oportunidad.
export async function getMotivosCierre(oppIds, accessToken) {
const motivos = {};
for (const batch of chunk(oppIds, 150)) {
if (!batch.length) continue;
const conditions = batch.map((id) => `${id}`).join("");
const fetchXml =
`` +
`` +
`` +
`` +
`${conditions}` +
``;
const data = await dv(`opportunitycloses?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
for (const r of data.value || []) {
const oid = r["_opportunityid_value"];
const created = r.createdon;
if (motivos[oid] && motivos[oid].createdon >= created) continue;
motivos[oid] = {
createdon: created,
motivo: fv(r, "alfa_motivodecierre") || fv(r, "opportunitystatuscode") || null,
competidor: fv(r, "_alfa_competitor_value"),
};
}
}
return motivos;
}
// Resuelve una lista de emails a systemuserids (en paralelo) y arma la cláusula OR
// `(_ownerid_value eq id1 or _ownerid_value eq id2 ...)` — multi-propietario, ver CLAUDE.md/authz.js.
async function resolveOwnerIds(emails, accessToken) {
const ids = await Promise.all(emails.map((e) => resolveOwnerId(e, accessToken)));
return ids.filter(Boolean);
}
function ownerOrClause(ids) {
return `(${ids.map((id) => `_ownerid_value eq ${id}`).join(" or ")})`;
}
// scope: { emails, locked } de ownerFilter(). emails=[] (admin, "todos") no filtra por propietario.
// typeFilter: PIPE_TYPE_FILTER (ventas, default) o REN_TYPE_FILTER (renovaciones).
async function getPipelineOfType(accessToken, scope, typeFilter) {
let filter = `statecode eq 0 and estimatedclosedate ne null and msdyn_forecastcategory ne 100000001 and ${typeFilter}`;
if (scope.emails?.length) {
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
if (!ownerIds.length) return [];
filter += ` and ${ownerOrClause(ownerIds)}`;
}
const data = await dv(
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
accessToken
);
const rows = (data.value || []).map(mapOpportunityRow);
const faseMap = await getFaseActual(rows.map((r) => r.id), accessToken);
const today = new Date();
return rows.map((r) => derivePipelineRow(r, faseMap[r.id], today));
}
export async function getPipeline(accessToken, scope) {
return getPipelineOfType(accessToken, scope, PIPE_TYPE_FILTER);
}
export async function getRenovPipeline(accessToken, scope) {
return getPipelineOfType(accessToken, scope, REN_TYPE_FILTER);
}
// 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: [] };
}
// 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).
export async function getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, typeFilter) {
const monthStart = `${month}-01`;
const [y, m] = month.split("-").map(Number);
const nextMonth = new Date(y, m, 1).toISOString().slice(0, 10);
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 (!ownerIds.length) return [];
filter += ` and ${ownerOrClause(ownerIds)}`;
}
const data = await dv(
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
accessToken
);
return (data.value || []).map(mapOpportunityRow);
}
export async function getRenovClosed(accessToken, scope, statecode, month, resolvedOwnerIds) {
return getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, REN_TYPE_FILTER);
}
// Ventana de historia para Actividades: statecode eq 0 (abierta, sin tope — es un plan de trabajo
// vivo) trae todo lo pendiente; scheduledend ge acota lo cerrado/cancelado a los últimos
// 90 días para no traer años de historial en cada carga (mismo patrón que build_actividades.js del
// sitio HTML, que usa un corte de fecha fijo en vez de "siempre todo").
const ACTIVIDADES_DIAS_HISTORIA = 90;
const ACTIVIDAD_ENTIDADES = [
{ entity: "tasks", tipo: "Tarea", navProp: "regardingobjectid_opportunity_task", propioField: "prioritycode", propioLabel: "Prioridad" },
{ entity: "appointments", tipo: "Cita", navProp: "regardingobjectid_opportunity_appointment", propioField: "location", propioLabel: "Ubicación" },
{ entity: "phonecalls", tipo: "Llamada", navProp: "regardingobjectid_opportunity_phonecall", propioField: "directioncode", propioLabel: "Dirección" },
];
function estadoBase(statecode) {
if (statecode === 1) return "completada";
if (statecode === 2) return "cancelada";
return "abierta"; // 0=Abierto, 3=Programado (Cita) — ambas "no cerradas" a efectos de negocio
}
function mapActividadRow(r, tipo, navProp, propioField, propioLabel) {
const tipoRef = lookupType(r, "_regardingobjectid_value");
const nombreRef = fv(r, "_regardingobjectid_value");
const objetivo = fv(r, "_alfa_objetivodeactividad_value");
const opp = r[navProp];
const propioValor = propioField === "location" ? r.location || null : fv(r, propioField);
return {
id: r.activityid,
tipo,
owner: fv(r, "_ownerid_value"),
asunto: r.subject || "(sin asunto)",
scheduledstart: r.scheduledstart || null,
scheduledend: r.scheduledend || null,
scheduledstartFmt: fv(r, "scheduledstart"),
scheduledendFmt: fv(r, "scheduledend"),
estado: estadoBase(r.statecode),
objetivo,
etapa: objetivo ? OBJETIVO_A_ETAPA[objetivo] || null : null,
referente: tipoRef && nombreRef ? { tipo: tipoRef, nombre: nombreRef, id: r._regardingobjectid_value } : null,
campoPropio: { label: propioLabel, valor: propioValor },
ingresoEstimado: opp && typeof opp.estimatedvalue === "number" ? opp.estimatedvalue : null,
tipoOportunidad: opp ? fv(opp, "alfa_typeopportunity") : null,
};
}
// scope: { email, locked }. email null (admin, "todos") trae los ejecutivos de venta curados —
// mismo alcance que el resto del informe (EJECUTIVOS_VENTA), resuelto en vivo contra systemusers
// en vez de una tabla fija de GUID (que es lo que hacía el ETL estático y quedaba desactualizada).
const COHORTE_SELECT = [
"opportunityid", "name", "createdon", "statecode", "actualclosedate", "estimatedclosedate",
"alfa_typeopportunity", "alfa_tipodeventa", "_ownerid_value", "_customerid_value",
"_alfa_lineadenegocioid_value", "_campaignid_value", "estimatedvalue", "actualvalue",
].join(",");
function mapCohorteRow(o) {
const tipo = fv(o, "alfa_typeopportunity");
const creada = o.createdon ? o.createdon.slice(0, 10) : null;
const estado = o.statecode === 1 ? "Ganada" : o.statecode === 2 ? "Perdida" : "Abierta";
const cierre = o.actualclosedate ? o.actualclosedate.slice(0, 10) : null;
const hoy = new Date().toISOString().slice(0, 10);
const diasEntre = (a, b) => (a && b ? Math.round((new Date(b) - new Date(a)) / 86400000) : null);
return {
id: o.opportunityid,
name: o.name,
owner: fv(o, "_ownerid_value"),
cliente: fv(o, "_customerid_value"),
creada,
mesCohorte: creada ? creada.slice(0, 7) : null,
estado,
cierre,
tipo,
segmento: segmentoDe(tipo),
origen: fv(o, "alfa_tipodeventa"),
linea: fv(o, "_alfa_lineadenegocioid_value"),
campaign: fv(o, "_campaignid_value"),
est: o.estimatedvalue || 0,
val: o.actualvalue || 0,
diasACierre: estado !== "Abierta" ? diasEntre(creada, cierre) : null,
diasAbierta: estado === "Abierta" ? diasEntre(creada, hoy) : null,
};
}
// scope: { email, locked }. mesesAtras: ventana de creación — el sitio HTML deja elegir el rango;
// acá se fija a 6 meses para acotar el volumen de la consulta en vivo (createdon no tiene índice
// de "top N recientes" propio, así que sin tope esto podría traer años de historial).
export async function getCohorte(accessToken, scope, mesesAtras = 6) {
const desde = new Date();
desde.setMonth(desde.getMonth() - mesesAtras);
desde.setDate(1);
const filterDesde = desde.toISOString().slice(0, 10);
let filter = `createdon ge ${filterDesde}`;
if (scope.emails?.length) {
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
if (!ownerIds.length) return [];
filter += ` and ${ownerOrClause(ownerIds)}`;
}
const data = await dv(
`opportunities?$select=${COHORTE_SELECT}&$filter=${encodeURIComponent(filter)}&$top=5000`,
accessToken
);
return (data.value || []).map(mapCohorteRow);
}
// roster: lista de nombres a incluir cuando no hay un solo propietario en `scope` (default
// EJECUTIVOS_VENTA) — Renovaciones pasa EJECUTIVOS_RENOV (Ventas + SAC, ver CLAUDE.md) para no
// perderse las actividades de SAC en el cruce "¿Ya se agendó algo?".
export async function getActividades(accessToken, scope, roster = EJECUTIVOS_VENTA) {
let ownerIds;
if (scope.emails?.length) {
ownerIds = await resolveOwnerIds(scope.emails, accessToken);
} else {
const users = await getSystemUsers(accessToken);
ownerIds = users.filter((u) => roster.includes(u.name)).map((u) => u.id);
}
if (!ownerIds.length) return [];
const cutoff = new Date(Date.now() - ACTIVIDADES_DIAS_HISTORIA * 86400000).toISOString().slice(0, 10);
const ownerFilterStr = `(${ownerIds.map((id) => `_ownerid_value eq ${id}`).join(" or ")})`;
const filter = `(statecode eq 0 or scheduledend ge ${cutoff}) and ${ownerFilterStr}`;
const results = await Promise.all(
ACTIVIDAD_ENTIDADES.map(async ({ entity, tipo, navProp, propioField, propioLabel }) => {
// actualend/statuscode salieron del $select: se traían pero nada en la UI los lee — menos
// columnas por fila, Dataverse arma la respuesta más rápido (3 consultas en paralelo con
// $expand, la página más pesada de la app).
const select = [
"activityid", "subject", "scheduledstart", "scheduledend",
"statecode", "_ownerid_value", "_regardingobjectid_value",
"_alfa_objetivodeactividad_value", propioField,
];
const query =
`${entity}?$select=${select.join(",")}` +
`&$expand=${navProp}($select=estimatedvalue,alfa_typeopportunity)` +
`&$filter=${encodeURIComponent(filter)}&$top=5000`;
const data = await dv(query, accessToken);
return (data.value || []).map((r) => mapActividadRow(r, tipo, navProp, propioField, propioLabel));
})
);
return results.flat();
}