112 lines
5.9 KiB
JavaScript
112 lines
5.9 KiB
JavaScript
|
|
// Agendador — acceso a Dynamics (solo servidor). Todo se hace con el token del usuario conectado
|
||
|
|
// (derechos del propio usuario) y SIN caché: se valida con datos de este momento, no de hace 4 min.
|
||
|
|
import { dvFresh, dvWrite, odataString } from "./dataverse";
|
||
|
|
import { GC, GV_USUARIO } from "./participantes";
|
||
|
|
import { ENTIDAD_TIPO, aUtc, minAHora, horaAMin, AGENDADOR, asuntoDe, descripcionDe, actividadParaDe } from "./agendador";
|
||
|
|
|
||
|
|
// statuscode «Cancelada» de cada tipo (PLAYBOOK §10; probado en Dynamics el 2026-10-27).
|
||
|
|
const STATUS_CANCELADA = { Llamada: 3, Cita: 4, Tarea: 6 };
|
||
|
|
const NAV = {
|
||
|
|
Llamada: { referente: "regardingobjectid_opportunity_phonecall", objetivo: "alfa_ObjetivodeActividad_PhoneCall" },
|
||
|
|
Cita: { referente: "regardingobjectid_opportunity_appointment", objetivo: "alfa_ObjetivodeActividad_Appointment" },
|
||
|
|
Tarea: { referente: "regardingobjectid_opportunity_task", objetivo: "alfa_ObjetivodeActividad_Task" },
|
||
|
|
};
|
||
|
|
const estadoDe = (statecode) => (statecode === 1 ? "completada" : statecode === 2 ? "cancelada" : "abierta");
|
||
|
|
|
||
|
|
// nombre del objetivo → id, leído del catálogo de Dynamics (no se fijan GUID en el código).
|
||
|
|
export async function objetivosPorNombre(token) {
|
||
|
|
const d = await dvFresh("alfa_objetivosdeactividadeses?$select=alfa_objetivo,alfa_objetivosdeactividadesid&$top=100", token);
|
||
|
|
const m = new Map();
|
||
|
|
(d.value || []).forEach((r) => m.set(String(r.alfa_objetivo || "").trim(), r.alfa_objetivosdeactividadesid));
|
||
|
|
return m;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Actividades NO canceladas del ejecutivo cuya fecha cae en [desde, hasta] (días de Nicaragua).
|
||
|
|
export async function actividadesFrescas(token, ownerId, desde, hasta) {
|
||
|
|
const x = aUtc(desde, "00:00");
|
||
|
|
const y = aUtc(hasta, "23:59");
|
||
|
|
const filtro = `_ownerid_value eq ${ownerId} and statecode ne 2 and ((scheduledstart ge ${x} and scheduledstart le ${y}) or (scheduledend ge ${x} and scheduledend le ${y}))`;
|
||
|
|
const res = await Promise.all(
|
||
|
|
Object.entries(ENTIDAD_TIPO).map(async ([tipo, ent]) => {
|
||
|
|
const d = await dvFresh(
|
||
|
|
`${ent}?$select=activityid,scheduledstart,scheduledend,statecode,_regardingobjectid_value&$filter=${encodeURIComponent(filtro)}&$top=500`,
|
||
|
|
token
|
||
|
|
);
|
||
|
|
return (d.value || []).map((r) => ({
|
||
|
|
id: r.activityid,
|
||
|
|
tipo,
|
||
|
|
estado: estadoDe(r.statecode),
|
||
|
|
scheduledstart: r.scheduledstart || null,
|
||
|
|
scheduledend: r.scheduledend || null,
|
||
|
|
oppId: r._regardingobjectid_value || null,
|
||
|
|
}));
|
||
|
|
})
|
||
|
|
);
|
||
|
|
return res.flat();
|
||
|
|
}
|
||
|
|
|
||
|
|
// Oportunidades (abiertas o no) por id, de a 25.
|
||
|
|
export async function oportunidadesFrescas(token, ids) {
|
||
|
|
const m = new Map();
|
||
|
|
for (let i = 0; i < ids.length; i += 25) {
|
||
|
|
const trozo = ids.slice(i, i + 25);
|
||
|
|
const f = trozo.map((id) => `opportunityid eq ${odataString(id)}`).join(" or ");
|
||
|
|
const d = await dvFresh(
|
||
|
|
`opportunities?$select=opportunityid,name,statecode,alfa_typeopportunity,_ownerid_value&$filter=${encodeURIComponent(f)}`,
|
||
|
|
token
|
||
|
|
);
|
||
|
|
(d.value || []).forEach((o) =>
|
||
|
|
m.set(o.opportunityid, { id: o.opportunityid, nombre: o.name, abierta: o.statecode === 0, tipoCodigo: o.alfa_typeopportunity ?? null, ownerId: o._ownerid_value })
|
||
|
|
);
|
||
|
|
}
|
||
|
|
return m;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Crea UNA actividad ligada a la oportunidad, con el propietario de la oportunidad. Devuelve su id.
|
||
|
|
export async function crearActividad(token, it, opp, ownerId, objetivoId, creadoPor) {
|
||
|
|
const nav = NAV[it.tipo];
|
||
|
|
const body = {
|
||
|
|
subject: asuntoDe(it),
|
||
|
|
...(descripcionDe(it, creadoPor) ? { description: descripcionDe(it, creadoPor) } : {}),
|
||
|
|
alfa_actividadpara: actividadParaDe(opp.tipoCodigo),
|
||
|
|
"ownerid@odata.bind": `/systemusers(${ownerId})`,
|
||
|
|
[`${nav.referente}@odata.bind`]: `/opportunities(${it.oppId})`,
|
||
|
|
[`${nav.objetivo}@odata.bind`]: `/alfa_objetivosdeactividadeses(${objetivoId})`,
|
||
|
|
};
|
||
|
|
if (it.tipo === "Tarea") {
|
||
|
|
body.scheduledstart = aUtc(it.dia, minAHora(AGENDADOR.horaTarea));
|
||
|
|
body.scheduledend = body.scheduledstart;
|
||
|
|
} else {
|
||
|
|
body.scheduledstart = aUtc(it.dia, it.hora);
|
||
|
|
body.scheduledend = aUtc(it.dia, minAHora(horaAMin(it.hora) + AGENDADOR.duracion[it.tipo]));
|
||
|
|
// Visitas creadas por la app (Agendador y seguimiento): lugar «Oficina del cliente» por defecto (decisión de Marco, 2026-11-10).
|
||
|
|
if (it.tipo === "Cita") body.location = "Oficina del cliente";
|
||
|
|
// «Llamar de» y «Propietario» salen con el propietario de la oportunidad (`ownerid` arriba): Dynamics
|
||
|
|
// completa «de» solo. Verificado por Marco con llamadas reales del agendador (2026-11-06).
|
||
|
|
if (it.tipo === "Llamada") body.directioncode = true;
|
||
|
|
// «Con GV» (Gerencia Comercial participa): queda en el campo Participantes de la actividad. Solo llamadas y visitas.
|
||
|
|
if (it.gv) body.alfa_participantes = GC;
|
||
|
|
// Solo en CITAS: Marco entra como asistente obligatorio (máscara 5) y el propietario como organizador (7), para que
|
||
|
|
// la sincronización del servidor la lleve al Outlook del ejecutivo y Exchange envíe la invitación a Marco. Las llamadas
|
||
|
|
// no llegan al calendario, así que no llevan partes.
|
||
|
|
if (it.gv && it.tipo === "Cita") {
|
||
|
|
body.appointment_activity_parties = [
|
||
|
|
{ participationtypemask: 7, "partyid_systemuser@odata.bind": `/systemusers(${ownerId})` },
|
||
|
|
{ participationtypemask: 5, "partyid_systemuser@odata.bind": `/systemusers(${GV_USUARIO})` },
|
||
|
|
];
|
||
|
|
}
|
||
|
|
}
|
||
|
|
const r = await dvWrite("POST", `${ENTIDAD_TIPO[it.tipo]}?$select=activityid`, token, body);
|
||
|
|
return r.activityid;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Cancela una actividad creada por el agendador SOLO si sigue abierta (si ya se completó o canceló, no
|
||
|
|
// se toca). Devuelve "cancelada" | "ya cerrada".
|
||
|
|
export async function cancelarActividad(token, tipo, id) {
|
||
|
|
const ent = ENTIDAD_TIPO[tipo];
|
||
|
|
const d = await dvFresh(`${ent}(${odataString(id)})?$select=statecode`, token);
|
||
|
|
if (d.statecode === 1 || d.statecode === 2) return "ya cerrada";
|
||
|
|
await dvWrite("PATCH", `${ent}(${odataString(id)})`, token, { statecode: 2, statuscode: STATUS_CANCELADA[tipo] });
|
||
|
|
return "cancelada";
|
||
|
|
}
|