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

176 lines
8.4 KiB
JavaScript
Raw Permalink Normal View History

// Cuentas del CRM y creación de actividades «libres» (ligadas a una oportunidad o a una cuenta) — solo
// servidor. Todo con el token del usuario conectado y SIN caché: se lee y se valida con datos de este momento.
import { dvFresh, dvWrite, odataString, fv } from "./dataverse";
import { ENTIDAD_TIPO, aUtc, minAHora, horaAMin } from "./agendador";
import { formatCodigos } from "./participantes";
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 || ""));
// Propiedad de navegación «Referente a» de cada tipo de actividad, según a qué apunte.
const NAV = {
opportunity: {
Llamada: "regardingobjectid_opportunity_phonecall",
Cita: "regardingobjectid_opportunity_appointment",
Tarea: "regardingobjectid_opportunity_task",
},
account: {
Llamada: "regardingobjectid_account_phonecall",
Cita: "regardingobjectid_account_appointment",
Tarea: "regardingobjectid_account_task",
},
};
const ENTIDAD_REF = { opportunity: "opportunities", account: "accounts" };
const NAV_OBJETIVO = {
Llamada: "alfa_ObjetivodeActividad_PhoneCall",
Cita: "alfa_ObjetivodeActividad_Appointment",
Tarea: "alfa_ObjetivodeActividad_Task",
};
const limpiar = (q) => String(q || "").trim().slice(0, 60);
// Cuentas que contienen el texto en su nombre o nombre comercial.
export async function buscarCuentas(token, q, top = 25, ownerId = null) {
const t = odataString(limpiar(q));
if (t.length < 2) return [];
const dueno = ownerId ? ` and _ownerid_value eq ${ownerId}` : "";
const filtro = `(contains(name,'${t}') or contains(new_nombrecomercial,'${t}')) and statecode eq 0${dueno}`;
const d = await dvFresh(
`accounts?$select=accountid,name,new_nombrecomercial,telephone1,customertypecode,_ownerid_value&$filter=${encodeURIComponent(filtro)}&$orderby=name&$top=${top}`,
token
);
return (d.value || []).map((a) => ({
id: a.accountid,
nombre: a.name,
comercial: a.new_nombrecomercial && a.new_nombrecomercial !== a.name ? a.new_nombrecomercial : null,
telefono: a.telephone1 || null,
tipo: fv(a, "customertypecode"),
propietario: fv(a, "_ownerid_value"),
}));
}
// Oportunidades abiertas cuyo nombre o cliente contiene el texto. `ownerId` limita a las del ejecutivo (null = todas).
export async function buscarOportunidades(token, q, ownerId, top = 12) {
const t = odataString(limpiar(q));
if (t.length < 2) return [];
const dueno = ownerId ? ` and _ownerid_value eq ${ownerId}` : "";
const filtro = `statecode eq 0 and (contains(name,'${t}') or contains(customerid_account/name,'${t}'))${dueno}`;
const d = await dvFresh(
`opportunities?$select=opportunityid,name,estimatedvalue,_customerid_value,_ownerid_value&$filter=${encodeURIComponent(filtro)}&$orderby=modifiedon desc&$top=${top}`,
token
);
return (d.value || []).map((o) => ({
id: o.opportunityid,
nombre: o.name,
cliente: fv(o, "_customerid_value"),
valor: typeof o.estimatedvalue === "number" ? o.estimatedvalue : null,
propietario: fv(o, "_ownerid_value"),
}));
}
// Ficha de la cuenta: datos básicos, contactos, oportunidades abiertas y últimas actividades.
export async function leerCuenta(token, id) {
const a = await dvFresh(
`accounts(${odataString(id)})?$select=accountid,name,new_nombrecomercial,telephone1,emailaddress1,address1_line1,new_cuidad,customertypecode,businesstypecode,accountclassificationcode,alfa_clientevip,alfa_puntuaciontotal,createdon,_ownerid_value,statecode`,
token
);
const [contactos, opps] = await Promise.all([
dvFresh(
`contacts?$select=fullname,jobtitle,emailaddress1,mobilephone,telephone1&$filter=${encodeURIComponent(`_parentcustomerid_value eq ${a.accountid} and statecode eq 0`)}&$top=15`,
token
),
dvFresh(
`opportunities?$select=opportunityid,name,estimatedvalue,estimatedclosedate,msdyn_forecastcategory,alfa_typeopportunity,_ownerid_value&$filter=${encodeURIComponent(`_customerid_value eq ${a.accountid} and statecode eq 0`)}&$orderby=estimatedvalue desc&$top=30`,
token
),
]);
const oportunidades = (opps.value || []).map((o) => ({
id: o.opportunityid,
nombre: o.name,
valor: typeof o.estimatedvalue === "number" ? o.estimatedvalue : null,
cierre: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null,
forecast: fv(o, "msdyn_forecastcategory"),
tipo: fv(o, "alfa_typeopportunity"),
tipoCodigo: o.alfa_typeopportunity ?? null,
propietario: fv(o, "_ownerid_value"),
}));
// Últimas actividades de la cuenta y de sus oportunidades abiertas (máx. 20 referentes).
const refs = [a.accountid, ...oportunidades.slice(0, 19).map((o) => o.id)];
const filtroAct = `(${refs.map((r) => `_regardingobjectid_value eq ${r}`).join(" or ")})`;
const porTipo = await Promise.all(
Object.entries(ENTIDAD_TIPO).map(async ([tipo, ent]) => {
const d = await dvFresh(
`${ent}?$select=activityid,subject,statecode,scheduledstart,scheduledend,_ownerid_value,_regardingobjectid_value&$filter=${encodeURIComponent(filtroAct)}&$orderby=scheduledend desc&$top=10`,
token
);
return (d.value || []).map((r) => ({
id: r.activityid,
tipo,
asunto: r.subject || "(sin asunto)",
estado: r.statecode === 1 ? "completada" : r.statecode === 2 ? "cancelada" : "abierta",
scheduledstart: r.scheduledstart || null,
scheduledend: r.scheduledend || null,
owner: fv(r, "_ownerid_value") || "",
referente: fv(r, "_regardingobjectid_value") || null,
}));
})
);
const actividades = porTipo.flat().sort((x, y) => String(y.scheduledend || y.scheduledstart || "").localeCompare(String(x.scheduledend || x.scheduledstart || ""))).slice(0, 20);
return {
id: a.accountid,
nombre: a.name,
comercial: a.new_nombrecomercial && a.new_nombrecomercial !== a.name ? a.new_nombrecomercial : null,
telefono: a.telephone1 || null,
correo: a.emailaddress1 || null,
direccion: a.address1_line1 || null,
ciudad: fv(a, "new_cuidad"),
tipo: fv(a, "customertypecode"),
tipoCodigo: a.customertypecode ?? null,
nivel: fv(a, "businesstypecode"),
clasificacion: fv(a, "accountclassificationcode"),
vip: a.alfa_clientevip === 1 || fv(a, "alfa_clientevip") === "Sí",
puntuacion: typeof a.alfa_puntuaciontotal === "number" ? a.alfa_puntuaciontotal : null,
creada: a.createdon ? a.createdon.slice(0, 10) : null,
propietario: fv(a, "_ownerid_value"),
propietarioId: a._ownerid_value || null,
activa: a.statecode === 0,
contactos: (contactos.value || []).map((c) => ({ nombre: c.fullname, cargo: c.jobtitle || null, correo: c.emailaddress1 || null, movil: c.mobilephone || c.telephone1 || null })),
oportunidades,
actividades,
};
}
// Crea UNA actividad ligada a una oportunidad o a una cuenta, a la fecha y hora elegidas (sin las franjas
// del Agendador: aquí la persona decide su calendario, como en Outlook). Devuelve el id creado.
// Citas: la descripción queda vacía (es la invitación que se envía al contacto).
export async function crearActividadLibre(token, { tipo, referenteTipo, referenteId, asunto, objetivoId, ownerId, dia, hora, duracion, actividadPara, participantes = [], lugar = null }) {
const nav = NAV[referenteTipo]?.[tipo];
if (!nav) throw new Error("REFERENTE_NO_VALIDO");
const body = {
subject: asunto,
alfa_actividadpara: actividadPara,
"ownerid@odata.bind": `/systemusers(${ownerId})`,
[`${nav}@odata.bind`]: `/${ENTIDAD_REF[referenteTipo]}(${referenteId})`,
[`${NAV_OBJETIVO[tipo]}@odata.bind`]: `/alfa_objetivosdeactividadeses(${objetivoId})`,
};
if (tipo === "Tarea") {
body.scheduledstart = aUtc(dia, hora);
body.scheduledend = body.scheduledstart;
body.description = "Creada desde el informe comercial.";
} else {
body.scheduledstart = aUtc(dia, hora);
body.scheduledend = aUtc(dia, minAHora(horaAMin(hora) + duracion));
if (tipo === "Llamada") {
body.directioncode = true;
body.description = "Creada desde el informe comercial.";
}
}
// Participantes planificados: solo en visitas y llamadas (las tareas no tienen el campo). La oportunidad se actualiza al completar.
if ((tipo === "Cita" || tipo === "Llamada") && participantes.length) body.alfa_participantes = formatCodigos(participantes);
if (tipo === "Cita" && lugar) body.location = lugar;
const r = await dvWrite("POST", `${ENTIDAD_TIPO[tipo]}?$select=activityid`, token, body);
return r.activityid;
}