informe-comercial-alfa/app/components/actividades/ActividadesClient.js

181 lines
8.1 KiB
JavaScript

"use client";
import { useState, useMemo } from "react";
import { agg, aggOrd, ETAPA_ORDER, EJECUTIVOS_VENTA } from "../../lib/derive";
import { actividadUrl } from "../../lib/constants";
import Panel from "../pipeline/Panel";
const HORIZONTES = [
["hoy", "Hoy"], ["semana", "Esta semana"], ["semana_pasada", "Semana pasada"],
["mes", "Este mes"], ["mes_pasado", "Mes pasado"], ["todas", "Todas"],
];
function inicioSemana(d) {
const x = new Date(d);
const dow = (x.getDay() + 6) % 7;
x.setDate(x.getDate() - dow);
x.setHours(0, 0, 0, 0);
return x;
}
function enRango(fecha, horizonte) {
if (horizonte === "todas") return true;
if (!fecha) return false;
const f = new Date(fecha);
f.setHours(0, 0, 0, 0);
const hoy = new Date();
hoy.setHours(0, 0, 0, 0);
if (horizonte === "hoy") return f.getTime() === hoy.getTime();
if (horizonte === "semana" || horizonte === "semana_pasada") {
const lunes = inicioSemana(hoy);
if (horizonte === "semana_pasada") lunes.setDate(lunes.getDate() - 7);
const domingo = new Date(lunes);
domingo.setDate(lunes.getDate() + (horizonte === "semana" ? 6 : 6));
if (horizonte === "semana_pasada") domingo.setDate(lunes.getDate() + 6);
return f >= lunes && f <= domingo;
}
if (horizonte === "mes" || horizonte === "mes_pasado") {
const base = new Date(hoy.getFullYear(), hoy.getMonth() - (horizonte === "mes_pasado" ? 1 : 0), 1);
return f.getFullYear() === base.getFullYear() && f.getMonth() === base.getMonth();
}
return true;
}
function TablaTipo({ titulo, rows, locked }) {
if (!rows.length) return null;
return (
<div className="panel" style={{ marginBottom: 14 }}>
<h3>{titulo} — {rows.length}</h3>
<div className="tw">
<div className="ts">
<table>
<thead>
<tr>
<th>Asunto</th><th>Referente</th><th>Objetivo</th>
{!locked && <th>Ejecutivo</th>}
<th>Estado</th><th>Fecha</th>
</tr>
</thead>
<tbody>
{rows.map((a) => (
<tr key={a.id}>
<td><a className="opp" href={actividadUrl(a)} target="_blank" rel="noopener">{a.asunto}</a></td>
<td>{a.referente?.nombre || "—"}</td>
<td>{a.objetivo || "—"}</td>
{!locked && <td>{a.owner}</td>}
<td>
<span className={a.estadoFinal === "Vencida" ? "pierde" : a.estadoFinal === "Completada" ? "gana" : ""}>
{a.estadoFinal}
</span>
</td>
<td>{a.scheduledendFmt || a.scheduledstartFmt || "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}
export default function ActividadesClient({ actividades, locked }) {
const [horizonte, setHorizonte] = useState("mes");
const filtradas = useMemo(
() => actividades.filter((a) => enRango(a.fecha, horizonte)),
[actividades, horizonte]
);
const completadas = filtradas.filter((a) => a.estadoFinal === "Completada");
const vencidas = filtradas.filter((a) => a.estadoFinal === "Vencida");
const pendientes = filtradas.filter((a) => a.estadoFinal === "Pendiente");
const cumplimiento = filtradas.length ? Math.round((completadas.length / filtradas.length) * 100) : 0;
const conObjetivo = filtradas.filter((a) => a.objetivo).length;
const conOportunidad = filtradas.filter((a) => a.referente?.tipo === "opportunity");
const porEjecutivo = EJECUTIVOS_VENTA.map((nombre) => {
const propias = filtradas.filter((a) => a.owner === nombre);
const hechas = propias.filter((a) => a.estadoFinal === "Completada").length;
const pct = propias.length ? Math.round((hechas / propias.length) * 100) : null;
return { nombre, total: propias.length, hechas, pct };
}).sort((a, b) => (b.pct ?? -1) - (a.pct ?? -1));
// Oportunidades relacionadas — actividades que sí traen Ingreso Estimado/Tipo de Oportunidad
// vía $expand, agrupadas por la oportunidad referida.
const porOportunidad = new Map();
conOportunidad.forEach((a) => {
const k = a.referente.id;
if (!porOportunidad.has(k)) {
porOportunidad.set(k, { nombre: a.referente.nombre, tipo: a.tipoOportunidad, est: a.ingresoEstimado || 0, n: 0 });
}
porOportunidad.get(k).n++;
});
const oportunidadesRelacionadas = [...porOportunidad.values()].sort((a, b) => b.n - a.n).slice(0, 12);
return (
<>
<p className="hint" style={{ marginBottom: 8 }}>
No hay seguimiento registrado en el CRM ≠ no hubo seguimiento — la mayoría del contacto comercial se hace por
WhatsApp, que no está integrado a Dynamics (ver CLAUDE.md). Ventana de datos: últimos 90 días cerrados + todo
lo que sigue abierto.
</p>
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
{HORIZONTES.map(([k, l]) => (
<button key={k} className={horizonte === k ? "on" : ""} type="button" onClick={() => setHorizonte(k)}>{l}</button>
))}
</div>
<div className="kpis">
<div className="kpi"><span className="n">{filtradas.length}</span><span className="l">Actividades (sin canceladas)</span></div>
<div className="kpi"><span className="n">{cumplimiento}%</span><span className="l">Cumplimiento (completadas/total)</span></div>
<div className="kpi"><span className="n">{pendientes.length}</span><span className="l">Pendientes</span></div>
<div className="kpi"><span className="n pierde">{vencidas.length}</span><span className="l">Vencidas</span></div>
</div>
<p className="hint">
Con Objetivo de Actividad asignado: <b>{conObjetivo}</b> ({filtradas.length ? Math.round((conObjetivo / filtradas.length) * 100) : 0}%) —
adopción real del campo. Referidas a Oportunidad: <b>{conOportunidad.length}</b> ({filtradas.length ? Math.round((conOportunidad.length / filtradas.length) * 100) : 0}%).
</p>
<div className="grid2" style={{ marginTop: 18 }}>
<Panel title="Por Etapa" rows={aggOrd(filtradas, "etapa", ETAPA_ORDER)} hideMoney />
<Panel title="Por Tipo de Actividad" rows={agg(filtradas, "tipo")} hideMoney />
<div className="panel">
<h3>Cumplimiento por ejecutivo</h3>
<p className="hint">Completadas ÷ total de actividades (sin canceladas) de cada quien</p>
{porEjecutivo.map((r) => (
<div className="row static" key={r.nombre}>
<div className="bl"><span className="nm">{r.nombre}</span></div>
<div className="bar-cell">
<div
className={`bar-fill ${r.pct == null ? "" : r.pct >= 70 ? "" : r.pct >= 50 ? "alerta" : "pierde"}`}
style={{ width: `${Math.min(100, r.pct ?? 0)}%` }}
/>
</div>
<span className="v">{r.pct == null ? "n/d" : `${r.pct}%`}</span>
<span className="c">{r.hechas}/{r.total}</span>
</div>
))}
</div>
<div className="panel">
<h3>Oportunidades relacionadas</h3>
<p className="hint">Oportunidades con más actividades referidas en este período</p>
{oportunidadesRelacionadas.length ? oportunidadesRelacionadas.map((o) => (
<div className="row static" key={o.nombre}>
<div className="bl"><span className="nm">{o.nombre}</span></div>
<div className="bar-cell" />
<span className="v">{o.n} act.</span>
<span className="c">{o.tipo || "—"}</span>
</div>
)) : <p className="hint">Ninguna actividad de este período está referida a una Oportunidad.</p>}
</div>
</div>
<div className="sec-div"><span>Detalle</span></div>
<TablaTipo titulo="Citas" rows={filtradas.filter((a) => a.tipo === "Cita")} locked={locked} />
<TablaTipo titulo="Llamadas" rows={filtradas.filter((a) => a.tipo === "Llamada")} locked={locked} />
<TablaTipo titulo="Tareas" rows={filtradas.filter((a) => a.tipo === "Tarea")} locked={locked} />
</>
);
}