"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 (
▼

{TIPO_LABEL_PLURAL[tipo] || tipo}

{rows.length} · {money(totalIngreso)} Ingreso Est. total
{!locked && } {sorted.map((a, i) => ( {!locked && } ))}
# Referente a Asunto Objetivo Fecha Inicio Fecha Vencimiento Ingreso Est. {propioLabel} EstadoPropietario
{i + 1} {a.referente?.nombre || "—"} {a.asunto} {a.objetivo || "—"} {a.scheduledstartFmt || "—"} {a.scheduledendFmt || "—"} {a.ingresoEstimado ? money(a.ingresoEstimado) : "—"} {a.campoPropio?.valor || "—"} ● {a.estadoFinal} {a.owner}
); } 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 ( <>
{HORIZONTES.map(([k, l]) => ( ))}
{filtradas.length}Actividades (sin canceladas)
{cumplimiento}%Cumplimiento (completadas/total)
{pendientes.length}Pendientes
{vencidas.length}Vencidas

Con Objetivo de Actividad asignado: {conObjetivo} ({filtradas.length ? Math.round((conObjetivo / filtradas.length) * 100) : 0}%) — adopción real del campo. Referidas a Oportunidad: {conOportunidad.length} ({filtradas.length ? Math.round((conOportunidad.length / filtradas.length) * 100) : 0}%).

ACT_TIPO_COLOR[k] || "var(--tinta-suave)"} />

Cumplimiento por ejecutivo

Completadas ÷ total de actividades (sin canceladas) de cada quien

{porEjecutivo.map((r) => (
{r.nombre}
= 70 ? "" : r.pct >= 50 ? "alerta" : "pierde"}`} style={{ width: `${Math.min(100, r.pct ?? 0)}%` }} />
{r.pct == null ? "n/d" : `${r.pct}%`} {r.hechas}/{r.total}
))}

Por Tipo de Oportunidad

{oportunidadesTotalN} oportunidades relacionadas en este período · {money(oportunidadesTotalV)} de ingreso estimado

{oportunidadesPorTipo.length ? oportunidadesPorTipo.map((r) => (
{r.k}
{r.n} {money(r.v)}
)) :

Ninguna actividad de este período está referida a una Oportunidad.

}
Detalle
a.tipo === "Cita")} locked={locked} /> a.tipo === "Llamada")} locked={locked} /> a.tipo === "Tarea")} locked={locked} /> ); }