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

220 lines
10 KiB
JavaScript

"use client";
import { useState, useMemo } from "react";
import { agg, aggOrd, ETAPA_ORDER, EJECUTIVOS_VENTA } from "../../lib/derive";
import { actividadUrl, money } from "../../lib/constants";
import Panel from "../pipeline/Panel";
import DonutChart from "../pipeline/DonutChart";
const HORIZONTES = [
["hoy", "Hoy"], ["semana", "Esta semana"], ["semana_pasada", "Semana pasada"],
["mes", "Este mes"], ["mes_pasado", "Mes pasado"], ["todas", "Todas"],
];
// Puerto de ACT_TIPO_COLOR/ACT_ESTADO_COLOR (App Informe/assets/js/pages/actividades.js).
const ACT_TIPO_COLOR = { Tarea: "var(--marca)", Cita: "var(--alerta)", Llamada: "var(--profundo)" };
const ACT_ESTADO_COLOR = { Completada: "var(--gana)", Vencida: "var(--pierde)", Pendiente: "var(--alerta)", Cancelada: "var(--tinta-suave)" };
const TIPO_LABEL_PLURAL = { Cita: "Citas", Llamada: "Llamadas", Tarea: "Tareas" };
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;
}
// Tabla de detalle agrupada por tipo, colapsable, con conteo + suma de Ingreso Est. en el
// encabezado — puerto de actSección() (App Informe/assets/js/pages/actividades.js). La columna
// "propia" (Ubicación/Prioridad/Dirección) cambia de nombre según el tipo — viene ya resuelta en
// `a.campoPropio` desde queries.js.
function DetalleTipo({ tipo, rows, locked }) {
if (!rows.length) return null;
const totalIngreso = rows.reduce((s, a) => s + (a.ingresoEstimado || 0), 0);
const sorted = [...rows].sort((a, b) => (a.scheduledstart || a.scheduledend || "").localeCompare(b.scheduledstart || b.scheduledend || ""));
const propioLabel = rows[0]?.campoPropio?.label || "";
return (
<details className="tw" open style={{ marginBottom: 16 }}>
<summary className="tw-title" style={{ cursor: "pointer" }}>
<span className="tw-chevron">▼</span>
<h3>{TIPO_LABEL_PLURAL[tipo] || tipo}</h3>
<span className="tw-count">{rows.length} · {money(totalIngreso)} Ingreso Est. total</span>
</summary>
<div className="ts">
<table>
<thead>
<tr>
<th>#</th>
<th>Referente a</th>
<th>Asunto</th>
<th>Objetivo</th>
<th>Fecha Inicio</th>
<th>Fecha Vencimiento</th>
<th className="num">Ingreso Est.</th>
<th>{propioLabel}</th>
<th>Estado</th>
{!locked && <th>Propietario</th>}
</tr>
</thead>
<tbody>
{sorted.map((a, i) => (
<tr key={a.id} style={a.estadoFinal === "Vencida" ? { background: "var(--pierde-soft)" } : undefined}>
<td>{i + 1}</td>
<td>{a.referente?.nombre || "—"}</td>
<td>
<a className="opp" href={actividadUrl(a)} target="_blank" rel="noopener">
{a.asunto}
</a>
</td>
<td>{a.objetivo || "—"}</td>
<td>{a.scheduledstartFmt || "—"}</td>
<td>{a.scheduledendFmt || "—"}</td>
<td className="num">{a.ingresoEstimado ? money(a.ingresoEstimado) : "—"}</td>
<td>{a.campoPropio?.valor || "—"}</td>
<td>
<span style={{ color: ACT_ESTADO_COLOR[a.estadoFinal] || "var(--tinta-suave)", fontWeight: 700 }}>
● {a.estadoFinal}
</span>
</td>
{!locked && <td>{a.owner}</td>}
</tr>
))}
</tbody>
</table>
</div>
</details>
);
}
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));
const tipoRows = agg(filtradas, "tipo");
// Por Tipo de Oportunidad — deduplica por oportunidad (una oportunidad con varias actividades
// referidas cuenta una sola vez), agrupa por tipoOportunidad. Puerto de
// actOportunidadesDedup()/actOportunidadesSection() del HTML.
const oportunidadesPorTipo = useMemo(() => {
const porOpp = new Map();
conOportunidad.forEach((a) => {
const k = a.referente.id;
if (!porOpp.has(k)) porOpp.set(k, { tipo: a.tipoOportunidad || "(sin dato)", est: a.ingresoEstimado || 0 });
});
const m = new Map();
porOpp.forEach((o) => {
const e = m.get(o.tipo) || { n: 0, v: 0 };
e.n++;
e.v += o.est;
m.set(o.tipo, e);
});
return [...m.entries()].map(([k, x]) => ({ k, ...x })).sort((a, b) => b.n - a.n);
}, [conOportunidad]);
const oportunidadesTotalN = oportunidadesPorTipo.reduce((s, r) => s + r.n, 0);
const oportunidadesTotalV = oportunidadesPorTipo.reduce((s, r) => s + r.v, 0);
return (
<>
<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 />
<DonutChart title="Por Tipo de Actividad" rows={tipoRows} colorFor={(k) => ACT_TIPO_COLOR[k] || "var(--tinta-suave)"} />
<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>Por Tipo de Oportunidad</h3>
<p className="hint">
{oportunidadesTotalN} oportunidades relacionadas en este período · {money(oportunidadesTotalV)} de ingreso estimado
</p>
{oportunidadesPorTipo.length ? oportunidadesPorTipo.map((r) => (
<div className="row dual static" key={r.k}>
<div className="bl"><span className="nm">{r.k}</span></div>
<div className="bar-cell">
<div className="bar-fill" style={{ width: `${oportunidadesTotalN ? (r.n / oportunidadesPorTipo[0].n) * 100 : 0}%` }} />
</div>
<span className="v">{r.n}</span>
<span className="c">{money(r.v)}</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>
<DetalleTipo tipo="Cita" rows={filtradas.filter((a) => a.tipo === "Cita")} locked={locked} />
<DetalleTipo tipo="Llamada" rows={filtradas.filter((a) => a.tipo === "Llamada")} locked={locked} />
<DetalleTipo tipo="Tarea" rows={filtradas.filter((a) => a.tipo === "Tarea")} locked={locked} />
</>
);
}