// App de campo (/m/...): acceso a Dynamics para las pantallas del teléfono — solo servidor. Todo con el token del usuario // conectado y SIN caché (dvFresh): contactos, ficha de oportunidad, cuentas, edición y notas. // Las reglas de negocio de actividades y participación NO se repiten: viven en actividadesServer.js y participantes.js. import { dvFresh, dvWrite, odataString, fv, lookupType } from "./dataverse"; import { notaLegible } from "./actividadesServer"; import { GC, parseCodigos, formatCodigos } from "./participantes"; import { destinosDe, categoriaDe, FORECAST_OPC, PROB_OPC, LUZ_OPC, TIPO_OPC, MAX_ESTADO_NEGOCIACION } from "./campo"; import { getFaseActual } from "./queries"; const enc = encodeURIComponent; const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; export const esGuid = (s) => GUID.test(String(s || "")); // Interruptor de emergencia de la edición de oportunidades desde el teléfono (variable de entorno en Coolify). export const edicionApagada = () => String(process.env.OPORTUNIDAD_EDICION || "").toLowerCase() === "off"; // ---- Contacto de una actividad / oportunidad / cuenta ---------------------------------------------------------- // Con quién hablar y cómo: contactos con número, teléfono y dirección de la cuenta. `tipo`: opportunity | account | incident. export async function leerContactoReferente(token, tipo, id) { let oppId = null; let oppNombre = null; let cuentaId = null; let principalId = null; let contactoDirecto = null; if (tipo === "opportunity") { const o = await dvFresh(`opportunities(${odataString(id)})?$select=name,_customerid_value,_parentcontactid_value`, token); oppId = id; oppNombre = o.name || null; principalId = o._parentcontactid_value || null; if (lookupType(o, "_customerid_value") === "contact") contactoDirecto = o._customerid_value; else cuentaId = o._customerid_value || null; } else if (tipo === "incident") { const c = await dvFresh(`incidents(${odataString(id)})?$select=title,_customerid_value`, token); if (lookupType(c, "_customerid_value") === "contact") contactoDirecto = c._customerid_value; else cuentaId = c._customerid_value || null; } else cuentaId = id; let cuenta = null; let contactos = []; if (cuentaId) { const [a, cs] = await Promise.all([ dvFresh(`accounts(${odataString(cuentaId)})?$select=accountid,name,telephone1,address1_line1,address1_city,new_cuidad,address1_latitude,address1_longitude,businesstypecode`, token), dvFresh(`contacts?$select=contactid,fullname,jobtitle,mobilephone,telephone1&$filter=${enc(`_parentcustomerid_value eq ${cuentaId} and statecode eq 0`)}&$top=40`, token), ]); cuenta = { id: a.accountid, nombre: a.name, telefono: a.telephone1 || null, direccion: a.address1_line1 || null, ciudad: fv(a, "new_cuidad") || a.address1_city || null, lat: typeof a.address1_latitude === "number" ? a.address1_latitude : null, lon: typeof a.address1_longitude === "number" ? a.address1_longitude : null, categoria: categoriaDe(a.businesstypecode), }; contactos = (cs.value || []).map((c) => ({ id: c.contactid, nombre: c.fullname, cargo: c.jobtitle || null, celular: c.mobilephone || null, fijo: c.telephone1 || null })); } else if (contactoDirecto) { const c = await dvFresh(`contacts(${odataString(contactoDirecto)})?$select=contactid,fullname,jobtitle,mobilephone,telephone1`, token); contactos = [{ id: c.contactid, nombre: c.fullname, cargo: c.jobtitle || null, celular: c.mobilephone || null, fijo: c.telephone1 || null }]; principalId = c.contactid; } return { oppId, oppNombre, cuenta, destinos: destinosDe({ contactos, principalId, cuenta }) }; } // ---- Ficha de oportunidad -------------------------------------------------------------------------------------- const OPP_FICHA = [ "opportunityid", "name", "statecode", "modifiedon", "estimatedvalue", "estimatedclosedate", "msdyn_forecastcategory", "alfa_typeopportunity", "_alfa_lineadenegocioid_value", "alfa_niveldeprobabilidad", "alfa_estadodelanegociacion", "alfa_plandecierre", "alfa_clasificaciondeoportunidad", "alfa_niveldeoportunidadestrellas", "alfa_luzamarilla", "_alfa_competidorid_value", "_customerid_value", "_ownerid_value", "_parentcontactid_value", "stepname", "alfa_diassinactividad", "alfa_participaciondegv", "alfa_participantes", ].join(","); const ACT_NOTA = { phonecalls: { tipo: "Llamada", sel: "activityid,subject,statecode,scheduledstart,scheduledend,actualend,description" }, appointments: { tipo: "Cita", sel: "activityid,subject,statecode,scheduledstart,scheduledend,actualend,alfa_resultadodelavisita,location" }, tasks: { tipo: "Tarea", sel: "activityid,subject,statecode,scheduledstart,scheduledend,actualend,description" }, }; export async function leerOportunidadFicha(token, id) { const o = await dvFresh(`opportunities(${odataString(id)})?$select=${OPP_FICHA}`, token); const clienteId = o._customerid_value || null; const esCuenta = lookupType(o, "_customerid_value") === "account"; const [fase, cuenta, notas, ...acts] = await Promise.all([ getFaseActual([id], token).catch(() => ({})), clienteId && esCuenta ? dvFresh(`accounts(${clienteId})?$select=name,businesstypecode`, token).catch(() => null) : Promise.resolve(null), dvFresh(`annotations?$select=annotationid,subject,notetext,createdon,_createdby_value&$filter=${enc(`_objectid_value eq ${id}`)}&$orderby=createdon desc&$top=30`, token).catch(() => ({ value: [] })), ...Object.entries(ACT_NOTA).map(([ent, m]) => dvFresh(`${ent}?$select=${m.sel}&$filter=${enc(`_regardingobjectid_value eq ${id} and statecode ne 2`)}&$orderby=scheduledend desc&$top=40`, token).catch(() => ({ value: [] })) ), ]); const hoyIso = new Date().toISOString(); const abiertas = []; const bitacora = []; Object.values(ACT_NOTA).forEach((m, i) => { for (const r of acts[i].value || []) { const completada = r.statecode === 1; if (completada) { const texto = notaLegible({ tipo: m.tipo, description: r.description, resultadoVisita: r.alfa_resultadodelavisita }); if (texto) bitacora.push({ k: "act", id: r.activityid, tipo: m.tipo, cuando: r.actualend || r.scheduledend || r.scheduledstart, texto }); } else { const inicio = m.tipo === "Tarea" ? r.scheduledend || r.scheduledstart : r.scheduledstart || r.scheduledend; if (inicio) abiertas.push({ id: r.activityid, tipo: m.tipo, inicio, asunto: r.subject }); } } }); for (const n of notas.value || []) { const texto = String(n.notetext || n.subject || "").trim(); if (texto) bitacora.push({ k: "nota", id: n.annotationid, cuando: n.createdon, texto: texto.slice(0, 1500), por: fv(n, "_createdby_value") }); } bitacora.sort((x, y) => String(y.cuando).localeCompare(String(x.cuando))); // Próxima actividad abierta: la más cercana en el futuro; si todas son pasadas, la más reciente vencida. abiertas.sort((x, y) => String(x.inicio).localeCompare(String(y.inicio))); const futura = abiertas.find((a) => a.inicio >= hoyIso) || abiertas[abiertas.length - 1] || null; const f = fase[id]; const diasEnFase = f?.started ? Math.round((Date.now() - new Date(f.started)) / 86400000) : null; const gv = o.alfa_participaciondegv === true; const parts = parseCodigos(o.alfa_participantes); return { id: o.opportunityid, etag: o["@odata.etag"] || null, nombre: o.name, abierta: o.statecode === 0, mrr: typeof o.estimatedvalue === "number" ? o.estimatedvalue : 0, cierre: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null, forecast: o.msdyn_forecastcategory ?? null, forecastTxt: fv(o, "msdyn_forecastcategory"), tipo: o.alfa_typeopportunity ?? null, tipoTxt: fv(o, "alfa_typeopportunity"), linea: fv(o, "_alfa_lineadenegocioid_value"), prob: o.alfa_niveldeprobabilidad ?? null, probTxt: fv(o, "alfa_niveldeprobabilidad"), estado: o.alfa_estadodelanegociacion || "", plan: fv(o, "alfa_plandecierre"), clasif: fv(o, "alfa_clasificaciondeoportunidad"), estrellas: o.alfa_niveldeoportunidadestrellas ?? null, luz: o.alfa_luzamarilla ?? null, luzTxt: fv(o, "alfa_luzamarilla"), competidorId: o._alfa_competidorid_value || null, competidor: fv(o, "_alfa_competidorid_value"), cliente: fv(o, "_customerid_value"), clienteId: esCuenta ? clienteId : null, categoria: categoriaDe(cuenta?.businesstypecode), ownerId: o._ownerid_value || null, owner: fv(o, "_ownerid_value"), fase: f?.fase || o.stepname || null, diasEnFase, diasSinActividad: o.alfa_diassinactividad ?? null, gv, participantes: parts, proxima: futura, bitacora: bitacora.slice(0, 25), }; } // ---- Edición de la oportunidad desde el teléfono ------------------------------------------------------------------ // Campos editables (verificados en metadatos 2026-11-13): previsión, tipo, nivel de probabilidad, cierre estimado, MRR // estimado, competidor, luz amarilla, participantes y estado de la negociación. NO: plan de cierre, clasificación (los // calcula un flujo), línea de negocio (solo lectura por decisión de Marco) ni ganar/perder. const VALIDOS = { forecast: new Set(FORECAST_OPC.map((x) => x[0])), tipo: new Set(TIPO_OPC.map((x) => x[0])), prob: new Set(PROB_OPC.map((x) => x[0])), luz: new Set(LUZ_OPC.map((x) => x[0])), }; // Lee la oportunidad con sus valores crudos y el etag (para armar el PATCH y poder deshacerlo). async function leerCrudo(token, id) { const o = await dvFresh(`opportunities(${odataString(id)})?$select=statecode,estimatedvalue,estimatedclosedate,msdyn_forecastcategory,alfa_typeopportunity,alfa_niveldeprobabilidad,alfa_luzamarilla,_alfa_competidorid_value,alfa_estadodelanegociacion,alfa_participaciondegv,alfa_participantes,_ownerid_value`, token); return { etag: o["@odata.etag"] || null, abierta: o.statecode === 0, ownerId: o._ownerid_value || null, forecast: o.msdyn_forecastcategory ?? null, tipo: o.alfa_typeopportunity ?? null, prob: o.alfa_niveldeprobabilidad ?? null, luz: o.alfa_luzamarilla ?? null, competidorId: o._alfa_competidorid_value || null, mrr: typeof o.estimatedvalue === "number" ? o.estimatedvalue : null, cierre: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null, estado: o.alfa_estadodelanegociacion ?? null, gv: o.alfa_participaciondegv === true, participantes: parseCodigos(o.alfa_participantes), }; } // Valida el cambio pedido y arma el PATCH solo con lo que de verdad cambió. Devuelve { campos, previo, nuevo } o { error }. export function armarCambios(actual, c) { const campos = {}; const previo = {}; const nuevo = {}; const poner = (k, campo, antes, ahora, valorCampo = ahora) => { previo[k] = antes; nuevo[k] = ahora; campos[campo] = valorCampo; }; if (c.forecast != null && c.forecast !== actual.forecast) { if (!VALIDOS.forecast.has(Number(c.forecast))) return { error: "Previsión no válida." }; poner("forecast", "msdyn_forecastcategory", actual.forecast, Number(c.forecast)); } if (c.tipo != null && c.tipo !== actual.tipo) { if (!VALIDOS.tipo.has(Number(c.tipo))) return { error: "Tipo de oportunidad no válido." }; poner("tipo", "alfa_typeopportunity", actual.tipo, Number(c.tipo)); } if (c.prob != null && c.prob !== actual.prob) { if (!VALIDOS.prob.has(Number(c.prob))) return { error: "Nivel de probabilidad no válido." }; poner("prob", "alfa_niveldeprobabilidad", actual.prob, Number(c.prob)); } if (c.luz != null && c.luz !== actual.luz) { if (!VALIDOS.luz.has(Number(c.luz))) return { error: "Luz amarilla no válida." }; poner("luz", "alfa_luzamarilla", actual.luz, Number(c.luz)); } if (c.cierre != null && c.cierre !== "" && c.cierre !== actual.cierre) { if (!/^\d{4}-\d{2}-\d{2}$/.test(String(c.cierre))) return { error: "La fecha de cierre no es válida." }; poner("cierre", "estimatedclosedate", actual.cierre, c.cierre); } if (c.mrr != null && c.mrr !== actual.mrr) { const m = Number(c.mrr); if (!Number.isFinite(m) || m < 0 || m > 1e7) return { error: "El MRR estimado no es válido." }; poner("mrr", "estimatedvalue", actual.mrr, Math.round(m * 100) / 100); } if (c.competidorId !== undefined && (c.competidorId || null) !== actual.competidorId) { if (c.competidorId && !esGuid(c.competidorId)) return { error: "Competidor no válido." }; previo.competidorId = actual.competidorId; nuevo.competidorId = c.competidorId || null; campos["alfa_competidorid@odata.bind"] = c.competidorId ? `/competitors(${c.competidorId})` : null; } if (c.estado != null && String(c.estado) !== String(actual.estado || "")) { const t = String(c.estado).slice(0, MAX_ESTADO_NEGOCIACION); poner("estado", "alfa_estadodelanegociacion", actual.estado ?? null, t || null); } if (Array.isArray(c.participantes)) { const pedidos = parseCodigos(c.participantes.join(",")); const pidenGV = pedidos.includes(GC); const otros = pedidos.filter((x) => x !== GC); if (pidenGV !== actual.gv) poner("gv", "alfa_participaciondegv", actual.gv, pidenGV); if (formatCodigos(otros) !== formatCodigos(actual.participantes)) poner("participantes", "alfa_participantes", actual.participantes, otros, otros.length ? formatCodigos(otros) : null); } return { campos, previo, nuevo }; } export async function editarOportunidad(token, id, etag, cambios, permitir) { const actual = await leerCrudo(token, id); if (!actual.abierta) return { error: "La oportunidad ya no está abierta." }; if (permitir && !(await permitir(actual.ownerId))) return { error: "Solo puedes editar tus propias oportunidades." }; const r = armarCambios(actual, cambios); if (r.error) return r; if (!Object.keys(r.campos).length) return { sinCambios: true, ownerId: actual.ownerId }; // If-Match con el etag que vio el teléfono al abrir la edición: si alguien la cambió mientras tanto, Dynamics responde 412. await dvWrite("PATCH", `opportunities(${odataString(id)})`, token, r.campos, etag ? { "If-Match": etag } : {}); return { ok: true, previo: r.previo, nuevo: r.nuevo, ownerId: actual.ownerId }; } // Deshace una edición: devuelve cada campo cambiado a su valor previo, solo si siguen como los dejó la edición. export async function restaurarOportunidad(token, id, previo, nuevo) { const actual = await leerCrudo(token, id); for (const k of Object.keys(nuevo)) { const hoy = k === "participantes" ? formatCodigos(actual.participantes) : actual[k]; const esperado = k === "participantes" ? formatCodigos(nuevo[k]) : nuevo[k]; if (hoy !== esperado && !(hoy == null && esperado == null)) return "CAMBIO"; } const r = armarCambios(actual, { ...(previo.forecast !== undefined ? { forecast: previo.forecast } : {}), ...(previo.tipo !== undefined ? { tipo: previo.tipo } : {}), ...(previo.prob !== undefined ? { prob: previo.prob } : {}), ...(previo.luz !== undefined ? { luz: previo.luz } : {}), ...(previo.cierre !== undefined ? { cierre: previo.cierre } : {}), ...(previo.mrr !== undefined ? { mrr: previo.mrr } : {}), ...(previo.competidorId !== undefined ? { competidorId: previo.competidorId } : {}), ...(previo.estado !== undefined ? { estado: previo.estado ?? "" } : {}), ...("gv" in previo || "participantes" in previo ? { participantes: [...(("gv" in previo ? previo.gv : actual.gv) ? [GC] : []), ...("participantes" in previo ? previo.participantes : actual.participantes)] } : {}), }); if (r.error) throw new Error(r.error); if (!Object.keys(r.campos).length) return "ok"; await dvWrite("PATCH", `opportunities(${odataString(id)})`, token, r.campos); return "ok"; } export async function buscarCompetidores(token, q) { const t = odataString(String(q || "").trim().slice(0, 40)); const filtro = t.length >= 1 ? `statecode eq 0 and contains(name,'${t}')` : "statecode eq 0"; const d = await dvFresh(`competitors?$select=competitorid,name&$filter=${enc(filtro)}&$orderby=name&$top=25`, token); return (d.value || []).map((c) => ({ id: c.competitorid, nombre: c.name })); } // ---- Notas nativas (annotation) ----------------------------------------------------------------------------------- export async function crearNota(token, oppId, texto, asunto = "Nota desde la app de campo") { const r = await dvWrite("POST", "annotations?$select=annotationid", token, { subject: String(asunto).slice(0, 200), notetext: String(texto).slice(0, 4000), "objectid_opportunity@odata.bind": `/opportunities(${odataString(oppId)})`, }); return r.annotationid; } export async function eliminarNota(token, notaId) { const r = await fetch(`${process.env.DATAVERSE_URL}/api/data/v9.2/annotations(${odataString(notaId)})`, { method: "DELETE", headers: { Authorization: `Bearer ${token}`, "OData-MaxVersion": "4.0", "OData-Version": "4.0" }, cache: "no-store", }); if (r.status === 401) throw new Error("TOKEN_EXPIRED"); if (!r.ok && r.status !== 404) throw new Error(`DATAVERSE_${r.status}`); } // ---- Cuentas -------------------------------------------------------------------------------------------------------- const CUENTA_SEL = "accountid,name,new_nombrecomercial,telephone1,customertypecode,businesstypecode,_ownerid_value"; const mapCuenta = (a) => ({ id: a.accountid, nombre: a.name, comercial: a.new_nombrecomercial && a.new_nombrecomercial !== a.name ? a.new_nombrecomercial : null, telefono: a.telephone1 || null, esCliente: a.customertypecode === 3, categoria: categoriaDe(a.businesstypecode), ownerId: a._ownerid_value || null, owner: fv(a, "_ownerid_value"), }); // Oportunidades abiertas agrupadas por cuenta: { cuentaId → { n, mrr } } — para «Con oportunidad» y la línea de contexto. export async function oportunidadesPorCuenta(token, ownerId) { const filtro = `statecode eq 0${ownerId ? ` and _ownerid_value eq ${ownerId}` : ""}`; const d = await dvFresh(`opportunities?$select=_customerid_value,estimatedvalue,name&$filter=${enc(filtro)}&$top=2000`, token); const m = new Map(); const nombres = new Map(); for (const o of d.value || []) { const c = o._customerid_value; if (!c || lookupType(o, "_customerid_value") !== "account") continue; const x = m.get(c) || { n: 0, mrr: 0 }; x.n++; x.mrr += typeof o.estimatedvalue === "number" ? o.estimatedvalue : 0; m.set(c, x); nombres.set(c, fv(o, "_customerid_value")); } return { m, nombres }; } // Lista de cuentas para la pantalla Cuentas. `filtro`: todas | clientes | opp | alta. `q`: texto (cuenta o contacto). export async function listarCuentas(token, { ownerId, q, filtro, top = 120, opps }) { const t = odataString(String(q || "").trim().slice(0, 60)); const partes = ["statecode eq 0"]; if (ownerId) partes.push(`_ownerid_value eq ${ownerId}`); if (filtro === "clientes") partes.push("customertypecode eq 3"); if (filtro === "alta") partes.push("(businesstypecode eq 200002 or businesstypecode eq 200000)"); let ids = null; if (filtro === "opp") { ids = [...opps.m.keys()]; if (!ids.length) return { cuentas: [], hayMas: false }; } if (t.length >= 2) { // También por contacto: cuentas cuyos contactos coinciden con el texto. const cc = await dvFresh(`contacts?$select=_parentcustomerid_value&$filter=${enc(`statecode eq 0 and contains(fullname,'${t}')`)}&$top=60`, token).catch(() => ({ value: [] })); const porContacto = [...new Set((cc.value || []).map((c) => c._parentcustomerid_value).filter(Boolean))]; const orId = porContacto.length ? ` or ${porContacto.map((x) => `accountid eq ${x}`).join(" or ")}` : ""; partes.push(`(contains(name,'${t}') or contains(new_nombrecomercial,'${t}')${orId})`); } const bloques = ids ? Array.from({ length: Math.ceil(ids.length / 25) }, (_, i) => ids.slice(i * 25, i * 25 + 25)) : [null]; const filas = []; for (const b of bloques) { const f = [...partes, ...(b ? [`(${b.map((x) => `accountid eq ${x}`).join(" or ")})`] : [])].join(" and "); const d = await dvFresh(`accounts?$select=${CUENTA_SEL}&$filter=${enc(f)}&$orderby=name&$top=${top + 1}`, token); filas.push(...(d.value || [])); if (!ids && filas.length > top) break; } const cuentas = filas.map(mapCuenta).sort((a, b) => a.nombre.localeCompare(b.nombre, "es")); return { cuentas: cuentas.slice(0, top), hayMas: cuentas.length > top }; }