247 lines
11 KiB
JavaScript
247 lines
11 KiB
JavaScript
|
|
// Plan del Día — arma las 5 secciones a partir de las actividades agendadas para un día.
|
|||
|
|
// Especificación: Proyectos/Análisis e Informes/Analitica de CRM/requerimientos-plan-del-dia.md
|
|||
|
|
import { actAncla } from "./derive";
|
|||
|
|
|
|||
|
|
// Hora de Nicaragua explícita (el servidor puede correr en otro huso).
|
|||
|
|
export function hoyManagua() {
|
|||
|
|
return new Intl.DateTimeFormat("en-CA", { timeZone: "America/Managua" }).format(new Date());
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export function addDays(iso, n) {
|
|||
|
|
const d = new Date(iso + "T12:00:00Z");
|
|||
|
|
d.setUTCDate(d.getUTCDate() + n);
|
|||
|
|
return d.toISOString().slice(0, 10);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Semana lunes–domingo que contiene `iso` (igual que el resto del informe).
|
|||
|
|
export function semanaDe(iso) {
|
|||
|
|
const dow = (new Date(iso + "T12:00:00Z").getUTCDay() + 6) % 7;
|
|||
|
|
const lunes = addDays(iso, -dow);
|
|||
|
|
return { lunes, domingo: addDays(lunes, 6) };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Día de la actividad: mismo criterio que Agenda/Actividades (ancla en Cita = inicio, Tarea/Llamada
|
|||
|
|
// = vencimiento; fecha tomada del ISO sin convertir de huso, igual que AgendaClient).
|
|||
|
|
export function diaDe(a) {
|
|||
|
|
const f = actAncla(a);
|
|||
|
|
return f ? String(f).slice(0, 10) : null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export const SECCIONES = [
|
|||
|
|
{ key: "cierre", titulo: "Cierre", sub: "Esperamos la aprobación de la oferta o el contrato firmado" },
|
|||
|
|
{ key: "negociacion", titulo: "Negociación para cierre", sub: "Objetivo Negociación" },
|
|||
|
|
{ key: "oferta", titulo: "Presentar oferta", sub: "Objetivo Presentar Oferta" },
|
|||
|
|
{ key: "seguimientos", titulo: "Seguimientos", sub: "Otras actividades ligadas a una oportunidad, caso o cuenta" },
|
|||
|
|
{ key: "renovaciones", titulo: "Renovaciones", sub: "Contrato vencido y próximo a vencer" },
|
|||
|
|
];
|
|||
|
|
|
|||
|
|
// Grupo "7. Administrativo" del catálogo de Objetivo de Actividad: no es trabajo comercial.
|
|||
|
|
const OBJ_ADMIN = new Set(["Planificación", "Gestión Admin.", "Otro"]);
|
|||
|
|
// Contrato Vencido (100000002) y Próximo a Vencer (100000001) — ver REN_TYPE_FILTER en queries.js.
|
|||
|
|
export const COD_RENOVACION = new Set([100000001, 100000002]);
|
|||
|
|
// Prioridad entre secciones de VENTAS cuando una misma oportunidad tiene varias actividades el
|
|||
|
|
// mismo día: gana la de menor número. Renovaciones va aparte (el tipo decide Ventas vs Renovación).
|
|||
|
|
const PRIORIDAD = { cierre: 0, negociacion: 1, oferta: 2, seguimientos: 3 };
|
|||
|
|
|
|||
|
|
// Sección por objetivo (sirve tanto para oportunidades como para casos/cuentas).
|
|||
|
|
function seccionPorObjetivo(objetivo) {
|
|||
|
|
if (objetivo === "Firma Contrato-Adendum") return "cierre";
|
|||
|
|
if (objetivo === "Negociación") return "negociacion";
|
|||
|
|
if (objetivo === "Presentar Oferta") return "oferta";
|
|||
|
|
return "seguimientos";
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Cierre = objetivo "Firma Contrato-Adendum", o la oportunidad está en forecast 80% (Proveedor
|
|||
|
|
// Confirmado) / 90% (Firma de contrato) — la etiqueta ya trae el % adelante, ver CLAUDE.md.
|
|||
|
|
function seccionDeOportunidad(a) {
|
|||
|
|
const opp = a.oportunidad;
|
|||
|
|
if (COD_RENOVACION.has(opp.tipoCodigo)) return "renovaciones";
|
|||
|
|
const pct = parseInt(opp.forecast || "", 10) || 0;
|
|||
|
|
if (pct === 80 || pct === 90) return "cierre";
|
|||
|
|
return seccionPorObjetivo(a.objetivo);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Entidades a las que puede apuntar "Referente a" sin ser oportunidad y que sí entran al plan
|
|||
|
|
// (decisión de Marco, 2026-10-26: Caso y Cuenta; sin valor estimado).
|
|||
|
|
const REF_SIN_OPP = new Set(["incident", "account"]);
|
|||
|
|
|
|||
|
|
// actividades: salida de getActividades(). dia: "YYYY-MM-DD". hoy: "YYYY-MM-DD" (para marcar
|
|||
|
|
// Vencida en días pasados). Devuelve { secciones: [{...SECCIONES[i], filas, subtotal}], resumen }.
|
|||
|
|
// Cada fila lleva `opp`: { id, etn, cliente, nombre, valor|null } — `valor` null = sin valor (caso/cuenta).
|
|||
|
|
export function armarPlan(actividades, dia, hoy) {
|
|||
|
|
const filas = new Map(); // oportunidad/caso/cuenta + propietario: una fila aunque tenga varias actividades
|
|||
|
|
for (const a of actividades) {
|
|||
|
|
if (a.estado === "cancelada") continue;
|
|||
|
|
if (diaDe(a) !== dia) continue;
|
|||
|
|
if (a.objetivo && OBJ_ADMIN.has(a.objetivo)) continue;
|
|||
|
|
|
|||
|
|
let ref, sec;
|
|||
|
|
if (a.oportunidad) {
|
|||
|
|
ref = { ...a.oportunidad, etn: "opportunity" };
|
|||
|
|
sec = seccionDeOportunidad(a);
|
|||
|
|
} else if (a.referente && REF_SIN_OPP.has(a.referente.tipo)) {
|
|||
|
|
ref = { id: a.referente.id, etn: a.referente.tipo, cliente: a.referente.nombre, nombre: a.referente.nombre, valor: null };
|
|||
|
|
sec = a.objetivo === "Renovación" ? "renovaciones" : seccionPorObjetivo(a.objetivo);
|
|||
|
|
} else continue;
|
|||
|
|
|
|||
|
|
const key = `${ref.id}|${a.owner}`;
|
|||
|
|
let r = filas.get(key);
|
|||
|
|
if (!r) {
|
|||
|
|
r = { key, sec, owner: a.owner, opp: ref, objetivos: [], acts: [] };
|
|||
|
|
filas.set(key, r);
|
|||
|
|
} else if (sec !== "renovaciones" && r.sec !== "renovaciones" && PRIORIDAD[sec] < PRIORIDAD[r.sec]) {
|
|||
|
|
r.sec = sec;
|
|||
|
|
}
|
|||
|
|
const obj = a.objetivo || "(sin objetivo)";
|
|||
|
|
if (!r.objetivos.includes(obj)) r.objetivos.push(obj);
|
|||
|
|
r.acts.push(a);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const secciones = SECCIONES.map((s) => {
|
|||
|
|
const rows = [...filas.values()]
|
|||
|
|
.filter((r) => r.sec === s.key)
|
|||
|
|
.map((r) => {
|
|||
|
|
const hechas = r.acts.filter((a) => a.estado === "completada").length;
|
|||
|
|
const total = r.acts.length;
|
|||
|
|
let estado = "Pendiente";
|
|||
|
|
if (hechas === total) estado = "Completada";
|
|||
|
|
else if (dia < hoy) estado = "Vencida";
|
|||
|
|
return { ...r, hechas, total, estado };
|
|||
|
|
})
|
|||
|
|
.sort((x, y) => x.owner.localeCompare(y.owner) || (y.opp.valor || 0) - (x.opp.valor || 0));
|
|||
|
|
return { ...s, filas: rows, subtotal: rows.reduce((t, r) => t + (r.opp.valor || 0), 0) };
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
const todas = secciones.flatMap((s) => s.filas);
|
|||
|
|
const actTotal = todas.reduce((t, r) => t + r.total, 0);
|
|||
|
|
const actHechas = todas.reduce((t, r) => t + r.hechas, 0);
|
|||
|
|
return { secciones, resumen: { oportunidades: todas.length, actTotal, actHechas } };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// ---- Plan cerrado (etapa 3) -------------------------------------------------------------------
|
|||
|
|
|
|||
|
|
// Foto del plan de UN ejecutivo: lo mínimo para comparar después (por id de actividad), no el
|
|||
|
|
// plan completo con sus campos de pantalla.
|
|||
|
|
export function crearFoto(plan, fecha) {
|
|||
|
|
const filas = plan.secciones.flatMap((s) =>
|
|||
|
|
s.filas.map((r) => ({
|
|||
|
|
sec: s.key,
|
|||
|
|
etn: r.opp.etn,
|
|||
|
|
id: r.opp.id,
|
|||
|
|
cliente: r.opp.cliente || r.opp.nombre || null,
|
|||
|
|
valor: r.opp.valor,
|
|||
|
|
acts: r.acts.map((a) => ({
|
|||
|
|
id: a.id,
|
|||
|
|
tipo: a.tipo,
|
|||
|
|
asunto: a.asunto,
|
|||
|
|
objetivo: a.objetivo || null,
|
|||
|
|
estado: a.estado,
|
|||
|
|
dia: diaDe(a),
|
|||
|
|
})),
|
|||
|
|
}))
|
|||
|
|
);
|
|||
|
|
return { fecha, filas, nActs: filas.reduce((t, f) => t + f.acts.length, 0) };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Foto contra realidad. Resultado por actividad de la foto:
|
|||
|
|
// Cumplida · No cumplida (sigue abierta, el día ya pasó) · Pendiente (hoy o futuro) ·
|
|||
|
|
// Reprogramada (sigue abierta pero ya no es de ese día) · Cancelada · Eliminada (ya no existe)
|
|||
|
|
// y «Agregada después» para lo que hoy está en el plan de ese día y no estaba en la foto.
|
|||
|
|
// `actividades` = getActividades() del ejecutivo (ventana de 90 días: una actividad más vieja que
|
|||
|
|
// eso aparecería como «Eliminada»); `plan` = armarPlan() actual de ese mismo día.
|
|||
|
|
export function compararConFoto(foto, actividades, plan, hoy) {
|
|||
|
|
const porId = new Map(actividades.map((a) => [a.id, a]));
|
|||
|
|
const enFoto = new Set();
|
|||
|
|
const lineas = [];
|
|||
|
|
for (const f of foto.filas) {
|
|||
|
|
for (const fa of f.acts) {
|
|||
|
|
enFoto.add(fa.id);
|
|||
|
|
const a = porId.get(fa.id);
|
|||
|
|
let res;
|
|||
|
|
let detalle = null;
|
|||
|
|
if (!a) res = "Eliminada";
|
|||
|
|
else if (a.estado === "cancelada") res = "Cancelada";
|
|||
|
|
else if (a.estado === "completada") res = "Cumplida";
|
|||
|
|
else {
|
|||
|
|
const dia = diaDe(a);
|
|||
|
|
if (dia && dia !== foto.fecha) {
|
|||
|
|
res = "Reprogramada";
|
|||
|
|
detalle = dia;
|
|||
|
|
} else res = foto.fecha < hoy ? "No cumplida" : "Pendiente";
|
|||
|
|
}
|
|||
|
|
lineas.push({ sec: f.sec, etn: f.etn, id: f.id, cliente: f.cliente, valor: f.valor, tipo: fa.tipo, asunto: fa.asunto, objetivo: fa.objetivo, res, detalle });
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
const agregadas = [];
|
|||
|
|
for (const s of plan.secciones) {
|
|||
|
|
for (const r of s.filas) {
|
|||
|
|
for (const a of r.acts) {
|
|||
|
|
if (enFoto.has(a.id)) continue;
|
|||
|
|
agregadas.push({
|
|||
|
|
sec: s.key, etn: r.opp.etn, id: r.opp.id, cliente: r.opp.cliente || r.opp.nombre || null, valor: r.opp.valor,
|
|||
|
|
tipo: a.tipo, asunto: a.asunto, objetivo: a.objetivo || null,
|
|||
|
|
res: a.estado === "completada" ? "Agregada después (cumplida)" : "Agregada después", detalle: null,
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
const cuenta = (r) => lineas.filter((l) => l.res === r).length;
|
|||
|
|
const resumen = {
|
|||
|
|
enFoto: lineas.length,
|
|||
|
|
cumplidas: cuenta("Cumplida"),
|
|||
|
|
noCumplidas: cuenta("No cumplida"),
|
|||
|
|
pendientes: cuenta("Pendiente"),
|
|||
|
|
reprogramadas: cuenta("Reprogramada"),
|
|||
|
|
canceladas: cuenta("Cancelada") + cuenta("Eliminada"),
|
|||
|
|
agregadas: agregadas.length,
|
|||
|
|
agregadasCumplidas: agregadas.filter((l) => l.res.includes("cumplida")).length,
|
|||
|
|
};
|
|||
|
|
return { lineas, agregadas, resumen };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Oportunidades abiertas con cierre estimado en la semana y SIN ninguna actividad ese día
|
|||
|
|
// (solo pantalla: invita al ejecutivo a agendar). `opps`: salida de getOportunidadesSemana().
|
|||
|
|
export function sinActividadAgendada(opps, actividades, dia) {
|
|||
|
|
const conActividad = new Set();
|
|||
|
|
for (const a of actividades) {
|
|||
|
|
if (a.estado === "cancelada" || !a.oportunidad || diaDe(a) !== dia) continue;
|
|||
|
|
conActividad.add(a.oportunidad.id);
|
|||
|
|
}
|
|||
|
|
return opps
|
|||
|
|
.filter((o) => !conActividad.has(o.id))
|
|||
|
|
.sort((x, y) => x.owner.localeCompare(y.owner) || x.cierre.localeCompare(y.cierre) || y.valor - x.valor);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Resumen por ejecutivo para el administrador (pantalla y PDF de equipo). `nombres`: ejecutivos a
|
|||
|
|
// listar; `ventas`/`renovaciones`: oportunidades ganadas del mes (getClosedRange).
|
|||
|
|
// Los totales de ventas/renovaciones salen de TODO lo ganado (como el encabezado); lo que no es de
|
|||
|
|
// los ejecutivos listados va en `otros` para que la tabla cuadre con el encabezado.
|
|||
|
|
export function resumenEquipo(plan, nombres, ventas, renovaciones) {
|
|||
|
|
const lineas = nombres.map((nombre) => {
|
|||
|
|
const secs = {};
|
|||
|
|
let actTotal = 0, actHechas = 0, valor = 0, items = 0;
|
|||
|
|
for (const s of plan.secciones) {
|
|||
|
|
const rows = s.filas.filter((r) => r.owner === nombre);
|
|||
|
|
secs[s.key] = { n: rows.length, valor: rows.reduce((t, r) => t + (r.opp.valor || 0), 0) };
|
|||
|
|
rows.forEach((r) => { actTotal += r.total; actHechas += r.hechas; });
|
|||
|
|
items += rows.length;
|
|||
|
|
valor += secs[s.key].valor;
|
|||
|
|
}
|
|||
|
|
const suma = (rows) => rows.filter((o) => o.owner === nombre).reduce((t, o) => t + (o.actual || 0), 0);
|
|||
|
|
return { nombre, secs, items, valor, actTotal, actHechas, ventasMes: suma(ventas), renovMes: suma(renovaciones) };
|
|||
|
|
});
|
|||
|
|
const total = { items: 0, valor: 0, actTotal: 0, actHechas: 0, ventasMes: 0, renovMes: 0, secs: {} };
|
|||
|
|
for (const s of plan.secciones) total.secs[s.key] = { n: 0, valor: 0 };
|
|||
|
|
for (const l of lineas) {
|
|||
|
|
total.items += l.items; total.valor += l.valor; total.actTotal += l.actTotal; total.actHechas += l.actHechas;
|
|||
|
|
for (const k of Object.keys(l.secs)) { total.secs[k].n += l.secs[k].n; total.secs[k].valor += l.secs[k].valor; }
|
|||
|
|
}
|
|||
|
|
const sumaTodo = (rows) => rows.reduce((t, o) => t + (o.actual || 0), 0);
|
|||
|
|
total.ventasMes = sumaTodo(ventas);
|
|||
|
|
total.renovMes = sumaTodo(renovaciones);
|
|||
|
|
const otrosV = total.ventasMes - lineas.reduce((t, l) => t + l.ventasMes, 0);
|
|||
|
|
const otrosR = total.renovMes - lineas.reduce((t, l) => t + l.renovMes, 0);
|
|||
|
|
const otros = Math.abs(otrosV) > 0.5 || Math.abs(otrosR) > 0.5 ? { ventasMes: otrosV, renovMes: otrosR } : null;
|
|||
|
|
return { lineas, total, otros };
|
|||
|
|
}
|