informe-comercial-alfa/app/lib/queries.js

503 lines
24 KiB
JavaScript

import { parseCodigos } from "./participantes";
import { dv, dvFresh, fv, lookupType, odataString } from "./dataverse";
import { derivePipelineRow, segmentoDe, normComp, normalizarFase, EJECUTIVOS_VENTA, OBJETIVO_A_ETAPA } from "./derive";
const OPP_SELECT = [
"opportunityid",
"modifiedon",
"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",
"prioritycode",
].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).
export 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(),
}));
}
// Un usuario puede entrar con @alfa.com.ni o con su UPN @alfaonline365.onmicrosoft.com, y en
// Dynamics el primero suele estar en internalemailaddress y el segundo en domainname. Se busca por
// ambos campos y por los dos dominios para que cualquiera de los correos resuelva al mismo usuario.
const DOMINIOS_ALFA = ["alfa.com.ni", "alfaonline365.onmicrosoft.com"];
function variantesCorreo(email) {
const e = email.trim().toLowerCase();
const [local, dominio] = e.split("@");
if (!local || !DOMINIOS_ALFA.includes(dominio)) return [e];
return DOMINIOS_ALFA.map((d) => `${local}@${d}`);
}
export async function resolveOwnerId(email, accessToken) {
if (!email) return null;
const cond = variantesCorreo(email)
.flatMap((v) => [`internalemailaddress eq '${odataString(v)}'`, `domainname eq '${odataString(v)}'`])
.join(" or ");
const data = await dv(
`systemusers?$select=systemuserid&$filter=${encodeURIComponent(`(${cond})`)}`,
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"),
ownerId: o._ownerid_value || null,
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,
// Última modificación del registro (cualquier cambio, también el de un flujo): se usa como indicio de «tubería al día».
modificada: o.modifiedon ? o.modifiedon.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,
// Prioridad: campo propio de Dynamics (`prioritycode`), la fija el ejecutivo; no se calcula.
prioridad: fv(o, "prioritycode") || "Sin prioridad",
};
}
export async function getFaseActual(oppIds, accessToken) {
const fase = {};
for (const batch of chunk(oppIds, 150)) {
if (!batch.length) continue;
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
const fetchXml =
`<fetch><entity name="alfa_stageduration">` +
`<attribute name="alfa_subject"/><attribute name="alfa_started"/><attribute name="alfa_opportunity"/>` +
`<filter><condition attribute="statuscode" operator="eq" value="1"/>` +
`<condition attribute="alfa_opportunity" operator="in">${conditions}</condition></filter>` +
`</entity></fetch>`;
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 = normalizarFase((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) {
// Oferta/Cotización/Proponer son una sola fase: si una oportunidad pasó por dos de ellas, se suman
// sus duraciones en un único tramo (clave oportunidad+fase) para no contarla dos veces.
const tramos = new Map();
for (const batch of chunk(oppIds, 150)) {
if (!batch.length) continue;
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
const fetchXml =
`<fetch><entity name="alfa_stageduration">` +
`<attribute name="alfa_subject"/><attribute name="alfa_duration"/><attribute name="alfa_opportunity"/>` +
`<filter><condition attribute="statuscode" operator="eq" value="100000000"/>` +
`<condition attribute="alfa_opportunity" operator="in">${conditions}</condition></filter>` +
`</entity></fetch>`;
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
const fase = normalizarFase(subj);
const k = `${oppId}|${fase}`;
const t = tramos.get(k);
if (t) t.dur += r.alfa_duration;
else tramos.set(k, { oppId, fase, dur: r.alfa_duration });
}
}
const out = [...tramos.values()];
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) => `<value>${id}</value>`).join("");
const fetchXml =
`<fetch><entity name="opportunityclose">` +
`<attribute name="opportunityid"/><attribute name="alfa_motivodecierre"/>` +
`<attribute name="opportunitystatuscode"/><attribute name="alfa_competitor"/>` +
`<attribute name="createdon"/>` +
`<filter><condition attribute="opportunityid" operator="in">${conditions}</condition></filter>` +
`</entity></fetch>`;
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.
export 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).
// scope.emails=[] ("todos") no filtra por propietario — cualquiera puede vender/renovar (incluida
// gente sin rol oficial de ventas pero con permiso para ciertos clientes, ver CLAUDE.md); el
// universo correcto de "ventas" lo da el typeFilter, no una lista fija de nombres.
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. fromDate/toDate: "YYYY-MM-DD", ventana de cierre real
// (actualclosedate) [fromDate, toDate). resolvedOwnerIds: opcional, ya resuelto vía
// resolveScopeOwnerIds — evita resolver los emails en cada llamada. typeFilter: opcional — sin él,
// trae cualquier tipo (Renovaciones pasa REN_TYPE_FILTER, Ventas pasa VENTA_TYPE_FILTER explícito).
export async function getClosedRange(accessToken, scope, statecode, fromDate, toDate, resolvedOwnerIds, typeFilter) {
let filter =
`statecode eq ${statecode} and actualclosedate ge ${fromDate} and actualclosedate lt ${toDate}`;
if (typeFilter) filter += ` and ${typeFilter}`;
if (scope.emails?.length) {
const ownerIds = resolvedOwnerIds !== undefined ? resolvedOwnerIds : 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);
}
// month: "YYYY-MM" — atajo de getClosedRange() para el mes calendario completo.
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);
return getClosedRange(accessToken, scope, statecode, monthStart, nextMonth, resolvedOwnerIds, typeFilter);
}
// Oportunidades abiertas (Ventas + Renovaciones) con cierre estimado en [desde, hasta] (fechas
// "YYYY-MM-DD", ambas incluidas). Consulta liviana para "Plan del Día": sin fase ni puntuación.
// Mismo filtro de forecast que la Tubería (excluye la categoría 0% Omitida, ver CLAUDE.md).
// Con `desde` y `hasta` en null trae TODAS las abiertas con fecha de cierre estimada (sin ventana): el
// agendador las usa para planificar una semana con lo que sigue abierto, no solo con lo que cierra ahí.
export async function getOportunidadesSemana(accessToken, scope, desde, hasta) {
let ventana = "estimatedclosedate ne null";
if (desde && hasta) {
const hastaExcl = new Date(hasta + "T12:00:00Z");
hastaExcl.setUTCDate(hastaExcl.getUTCDate() + 1);
ventana = `estimatedclosedate ge ${desde} and estimatedclosedate lt ${hastaExcl.toISOString().slice(0, 10)}`;
}
let filter =
`statecode eq 0 and ${ventana}` +
` and msdyn_forecastcategory ne 100000001 and (${PIPE_TYPE_FILTER} or ${REN_TYPE_FILTER})`;
if (scope.emails?.length) {
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
if (!ownerIds.length) return [];
filter += ` and ${ownerOrClause(ownerIds)}`;
}
const select = [
"opportunityid", "name", "_ownerid_value", "_customerid_value", "estimatedvalue",
"estimatedclosedate", "alfa_typeopportunity", "msdyn_forecastcategory", "alfa_plandecierre",
"alfa_envejecimiento", "alfa_diassinactividad",
].join(",");
const data = await dv(`opportunities?$select=${select}&$filter=${encodeURIComponent(filter)}&$top=1000`, accessToken);
return (data.value || []).map((o) => ({
id: o.opportunityid,
nombre: o.name,
owner: fv(o, "_ownerid_value") || "",
ownerId: o._ownerid_value || null,
cliente: fv(o, "_customerid_value"),
valor: o.estimatedvalue || 0,
cierre: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : "",
tipoCodigo: o.alfa_typeopportunity ?? null,
tipo: fv(o, "alfa_typeopportunity"),
plan: fv(o, "alfa_plandecierre"),
env: o.alfa_envejecimiento ?? null,
dsa: o.alfa_diassinactividad ?? null,
forecast: fv(o, "msdyn_forecastcategory"),
}));
}
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 <cutoff> 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),
participantes: parseCodigos(r.alfa_participantes),
enLinea: r.isonlinemeeting === true,
lugar: tipo === "Cita" ? r.location || null : null,
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,
// Datos de la oportunidad referida para "Plan del Día" (lib/plan.js): clasifica por tipo
// (código crudo, no la etiqueta) y por forecast, y muestra cliente y valor.
oportunidad: opp
? {
id: opp.opportunityid || r._regardingobjectid_value,
nombre: opp.name || null,
cliente: fv(opp, "_customerid_value"),
valor: typeof opp.estimatedvalue === "number" ? opp.estimatedvalue : 0,
tipoCodigo: opp.alfa_typeopportunity ?? null,
forecast: fv(opp, "msdyn_forecastcategory"),
cierre: opp.estimatedclosedate ? opp.estimatedclosedate.slice(0, 10) : null,
}
: 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?".
// `fresh`: sin caché de 4 min (la campanita lo usa justo después de gestionar una actividad).
export async function getActividades(accessToken, scope, roster = EJECUTIVOS_VENTA, { fresh = false } = {}) {
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,
];
// Participantes (visitas y llamadas; las tareas no los llevan) y si la visita tiene reunión de Teams vinculada.
if (tipo === "Cita") select.push("alfa_participantes", "isonlinemeeting");
if (tipo === "Llamada") select.push("alfa_participantes");
const query =
`${entity}?$select=${select.join(",")}` +
`&$expand=${navProp}($select=opportunityid,name,estimatedvalue,alfa_typeopportunity,msdyn_forecastcategory,estimatedclosedate,_customerid_value)` +
`&$filter=${encodeURIComponent(filter)}&$top=5000`;
const data = await (fresh ? dvFresh : dv)(query, accessToken);
return (data.value || []).map((r) => mapActividadRow(r, tipo, navProp, propioField, propioLabel));
})
);
return results.flat();
}