Agendador sugerido de la semana (piloto con María Auxiliadora): propuesta de llamadas/citas/tareas con topes y horario, creación en Dynamics con el propietario de la oportunidad, deshacer; rol de asistente acotado al piloto
This commit is contained in:
commit
ad2d69718a
110 changed files with 11182 additions and 0 deletions
11
.claude/launch.json
Normal file
11
.claude/launch.json
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
{
|
||||
"version": "0.0.1",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "informe-comercial-dev",
|
||||
"runtimeExecutable": "npm",
|
||||
"runtimeArgs": ["run", "dev"],
|
||||
"port": 3000
|
||||
}
|
||||
]
|
||||
}
|
||||
1
.claude/scheduled_tasks.lock
Normal file
1
.claude/scheduled_tasks.lock
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"sessionId":"e423c846-29e7-41ef-9e20-37bad045d6ba","pid":6112,"procStart":"134350917200947005","acquiredAt":1790621443967}
|
||||
10
.dockerignore
Normal file
10
.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
node_modules
|
||||
.next
|
||||
.git
|
||||
data
|
||||
__nm_old
|
||||
.nm_trash*
|
||||
*.log
|
||||
npm-debug.log*
|
||||
.env
|
||||
.env.local
|
||||
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
node_modules
|
||||
.next
|
||||
data
|
||||
__nm_old
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
.env.local
|
||||
9
AGENTS.md
Normal file
9
AGENTS.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
57
CLAUDE.md
Normal file
57
CLAUDE.md
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
@AGENTS.md
|
||||
|
||||
# Informe Comercial ALFA+ — app Next.js (Dataverse en vivo)
|
||||
|
||||
Dashboard comercial de **ALFA+** (Alfanumeric Nicaragua), consulta Dynamics 365 en vivo por OAuth
|
||||
de vendedor (`dynamic = "force-dynamic"`, sin caché) — reemplaza al sitio HTML estático que vive en
|
||||
`Proyectos/Análisis e Informes/Analitica de CRM/App Informe/` (archivado, solo referencia; los comentarios del
|
||||
código que citan `herramientas/…` o `App Informe/…` apuntan a ese material). Publicado en
|
||||
`https://informe-comercial.apps.online.com.ni`.
|
||||
|
||||
## ⚠️ Esta es la carpeta que corre en producción
|
||||
|
||||
**`C:\dev\informe-comercial` es la única carpeta de trabajo y la fuente real de lo publicado.** Es un
|
||||
repo git (rama `main`) sincronizado con Forgejo (`MarcoMontenegro/informe-comercial-alfa`). La copia
|
||||
anterior en `C:\Mis Aplicaciones\informe-comercial` se eliminó el 2026-09-28. Historial del tema en
|
||||
`Proyectos/Análisis e Informes/Analitica de CRM/sesion.md`, entrada "2026-09-28".
|
||||
|
||||
## ⚠️ Publicar y git — leer antes de tocar el repo local (2026-10-27)
|
||||
|
||||
- **`publish_changes` publica lo que hay en esta carpeta y sube su propio commit a Forgejo** (fuerza el push). El git local de esta carpeta queda **desfasado** (rama «adelante 1, atrás 1») y con cambios sin commit: es normal. **No hacer `git pull`, `git reset` ni `git checkout .` sin revisar**: perderías trabajo que ya está en producción.
|
||||
- Para saber si algo está publicado, no fiarse de `git status`: comparar los archivos con `origin/main` (`git fetch` y comparar hashes) o leer el commit desplegado en `get_logs`. El 2026-10-27 se comprobó así que los 104 archivos coinciden con el commit `0a51fac`.
|
||||
- **Dos sesiones pueden trabajar en paralelo en esta misma carpeta** (el 2026-10-27: una en Previsión de Ventas, otra en Plan del Día / enlaces). Como comparten el árbol de trabajo, lo que publique una incluye lo de la otra: avisar antes de publicar y revisar `git status` para no subir trabajo a medias.
|
||||
- **Enlaces para crear actividades en Dynamics** (`nuevaActividadUrl` en `app/lib/constants.js`): el tipo del «Referente a» va en `regardingobjectidtype=opportunity`. Con `regardingobjecttypecode` el formulario se ve bien pero **al guardar falla con 0x80040217**. Los correos de Power Automate usan el mismo enlace (corregidos el 2026-10-27).
|
||||
|
||||
## Filtro de propietario persistente y Plan del Día (2026-10-26)
|
||||
|
||||
Cómo quedaron hechos (archivos, reglas de clasificación, PDF Carta horizontal, decisiones) y cómo reutilizarlos:
|
||||
`Proyectos/Análisis e Informes/Analitica de CRM/referencia-implementacion-plan-del-dia.md` — la especificación funcional
|
||||
está en `requerimientos-plan-del-dia.md` de esa misma carpeta. Código: `app/plan/`, `app/lib/plan.js`,
|
||||
`app/components/plan/`, `app/components/OwnerControl.js`.
|
||||
|
||||
## Reglas de negocio — viven en el proyecto de análisis, no acá
|
||||
|
||||
**No duplicar aquí** la definición de tipos de oportunidad, tuberías, forecast category, motivos de
|
||||
cierre, ejecutivos de venta, ni las lecciones aprendidas de interpretación de datos. Esa es la
|
||||
fuente de verdad y cambia con el negocio — leerla ahí:
|
||||
|
||||
📘 `C:\Users\marco.montenegro\OneDrive - Alfanumeric\Claude\Proyectos\Análisis e Informes\Analitica de CRM\CLAUDE.md`
|
||||
|
||||
De ahí en particular:
|
||||
- Estructura de tuberías y tipos de oportunidad (`alfa_typeopportunity`)
|
||||
- **Cumplimiento de meta — qué cuenta**: solo Venta - Cliente Nuevo, Up-Selling, Cross-Selling,
|
||||
Plan de Cuenta (`TIPOS_META` en `app/lib/derive.js` es el espejo en código de esa lista)
|
||||
- Ejecutivos de venta reales — Gabriela Sánchez y Ashley Bermúdez aparecen en los datos pero **no**
|
||||
son ejecutivas de venta (`EJECUTIVOS_VENTA` en `app/lib/derive.js`)
|
||||
- Forecast category con escala propia de ALFA+ (no la estándar de Dynamics)
|
||||
- El mapa de motivos de cierre (`MOTIVO_MAP`) — Dynamics reetiquetó el optionset en sep-2026
|
||||
- Las advertencias de interpretación (WhatsApp no está en el CRM, promedio ≠ techo, etc.)
|
||||
|
||||
Si una regla de negocio de código acá (`app/lib/derive.js`, `app/lib/queries.js`) no cuadra con lo
|
||||
que dice ese `CLAUDE.md`, **ese archivo manda** — el código se ajusta a él, no al revés.
|
||||
|
||||
## Entorno técnico (ALFA+, común a todos los proyectos)
|
||||
|
||||
Ver también el `CLAUDE.md` raíz de ALFA+ (`Claude/CLAUDE.md`) para Dynamics
|
||||
(`alfanumeric.crm.dynamics.com`), convenciones de trabajo (todo en español, no inventar números,
|
||||
cambios acotados) y marca.
|
||||
23
Dockerfile
Normal file
23
Dockerfile
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
# syntax=docker/dockerfile:1.7
|
||||
# Debian slim (glibc), no Alpine: el build de Coolify no puede bajar el binario precompilado de
|
||||
# better-sqlite3 (sin red saliente durante npm ci), así que igual compila con node-gyp — pero
|
||||
# node:22-alpine actual trae Python 3.14, incompatible con la toolchain de compilación de gyp;
|
||||
# Debian slim trae una versión de Python compatible (ver Proyectos/Analitica de CRM/sesion.md,
|
||||
# 2026-09-28).
|
||||
FROM node:22-slim
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY package.json package-lock.json ./
|
||||
# --mount=type=cache persiste el cache de npm/de build de Next entre deploys en el mismo host de
|
||||
# Coolify (BuildKit) — evita re-descargar el registry completo y recompilar todo Next.js desde cero
|
||||
# cuando solo cambió código de la app, no dependencias. npm ci en vez de npm install: no resuelve
|
||||
# versiones (usa el lockfile tal cual), más rápido y determinístico para build reproducible.
|
||||
RUN --mount=type=cache,target=/root/.npm npm ci
|
||||
COPY . .
|
||||
RUN --mount=type=cache,target=/app/.next/cache npm run build
|
||||
EXPOSE 3000
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
CMD ["npm", "start"]
|
||||
158
app/actividades/agendadorActions.js
Normal file
158
app/actividades/agendadorActions.js
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "../lib/auth";
|
||||
import { puedeAgendarPara } from "../lib/authz";
|
||||
import { resolveOwnerId, getSystemUsers } from "../lib/queries";
|
||||
import { hoyManagua, rangoPeriodoAct, diasDelRango, esHabil } from "../lib/plan";
|
||||
import { TIPOS_AGENDADOR, OBJETIVOS_AGENDADOR, validar, resumenExistentes, localDeIso } from "../lib/agendador";
|
||||
import {
|
||||
objetivosPorNombre, actividadesFrescas, oportunidadesFrescas, crearActividad, cancelarActividad,
|
||||
} from "../lib/agendadorServer";
|
||||
import { guardarLote, getLote, marcarDeshecho } from "../lib/agendadorLotes";
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const MAX_ITEMS = 40;
|
||||
|
||||
const refrescar = () => {
|
||||
revalidatePath("/actividades");
|
||||
revalidatePath("/plan");
|
||||
revalidatePath("/prevision");
|
||||
};
|
||||
|
||||
const errorDe = (e) =>
|
||||
e?.message === "TOKEN_EXPIRED"
|
||||
? "Tu sesión expiró. Vuelve a iniciar sesión y reintenta."
|
||||
: "No se pudo completar la operación en Dynamics. Intenta de nuevo.";
|
||||
|
||||
// Crea en Dynamics las actividades propuestas por el agendador. El navegador solo manda QUÉ quiere
|
||||
// (oportunidad, tipo, objetivo, día, hora): todo lo demás se vuelve a verificar AQUÍ, con datos de este
|
||||
// momento — permisos, semana, que la oportunidad esté abierta y sea del ejecutivo, topes por día,
|
||||
// horarios, que no se encime ni duplique. Si algo no cuadra, NO se crea nada.
|
||||
export async function crearLoteAction({ ownerEmail, periodo, items }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión para agendar." };
|
||||
const owner = String(ownerEmail || "").toLowerCase();
|
||||
if (!puedeAgendarPara(session, owner)) return { ok: false, error: "No tienes permiso para agendar para este ejecutivo." };
|
||||
|
||||
const hoy = hoyManagua();
|
||||
const rango = rangoPeriodoAct(String(periodo || ""), hoy);
|
||||
if (rango.tipo !== "semana" || rango.hasta < hoy) return { ok: false, error: "El agendador solo funciona en una semana actual o futura." };
|
||||
const desdeDias = rango.desde > hoy ? rango.desde : hoy;
|
||||
const dias = diasDelRango(desdeDias, rango.hasta).filter(esHabil);
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||||
|
||||
if (!Array.isArray(items) || !items.length) return { ok: false, error: "No hay actividades para crear." };
|
||||
if (items.length > MAX_ITEMS) return { ok: false, error: `Máximo ${MAX_ITEMS} actividades por tanda.` };
|
||||
const limpios = items.map((i) => ({
|
||||
key: String(i?.oppId || ""),
|
||||
oppId: String(i?.oppId || ""),
|
||||
nombre: String(i?.nombre || "").slice(0, 200),
|
||||
cliente: i?.cliente ? String(i.cliente).slice(0, 200) : null,
|
||||
tipo: String(i?.tipo || ""),
|
||||
objetivo: String(i?.objetivo || ""),
|
||||
dia: String(i?.dia || ""),
|
||||
hora: String(i?.hora || ""),
|
||||
}));
|
||||
if (limpios.some((i) => !UUID.test(i.oppId))) return { ok: false, error: "Hay una oportunidad no válida en la lista." };
|
||||
if (new Set(limpios.map((i) => i.oppId)).size !== limpios.length) return { ok: false, error: "Una oportunidad aparece más de una vez." };
|
||||
if (limpios.some((i) => !TIPOS_AGENDADOR.includes(i.tipo) || !OBJETIVOS_AGENDADOR.includes(i.objetivo))) {
|
||||
return { ok: false, error: "Hay un tipo u objetivo no permitido." };
|
||||
}
|
||||
|
||||
try {
|
||||
const token = session.accessToken;
|
||||
const ownerId = await resolveOwnerId(owner, token);
|
||||
if (!ownerId) return { ok: false, error: "No encontré al ejecutivo en Dynamics." };
|
||||
const [opps, acts, objetivos, users] = await Promise.all([
|
||||
oportunidadesFrescas(token, limpios.map((i) => i.oppId)),
|
||||
actividadesFrescas(token, ownerId, rango.desde, rango.hasta),
|
||||
objetivosPorNombre(token),
|
||||
getSystemUsers(token),
|
||||
]);
|
||||
const ownerName = users.find((u) => u.id === ownerId)?.name || owner;
|
||||
|
||||
// Cada oportunidad debe estar abierta y ser del ejecutivo; si ya tiene algo pendiente esta semana, se omite.
|
||||
const pendientes = new Set(acts.filter((a) => a.estado === "abierta" && a.oppId).map((a) => a.oppId));
|
||||
const resultados = [];
|
||||
const aCrear = [];
|
||||
for (const it of limpios) {
|
||||
const o = opps.get(it.oppId);
|
||||
if (!o || !o.abierta) { resultados.push({ ...it, estado: "omitida", error: "La oportunidad no está abierta." }); continue; }
|
||||
if (o.ownerId !== ownerId) { resultados.push({ ...it, estado: "omitida", error: "La oportunidad no es de este ejecutivo." }); continue; }
|
||||
if (pendientes.has(it.oppId)) { resultados.push({ ...it, estado: "omitida", error: "Ya tiene una actividad pendiente esta semana." }); continue; }
|
||||
if (!objetivos.get(it.objetivo)) { resultados.push({ ...it, estado: "omitida", error: "No encontré ese objetivo en Dynamics." }); continue; }
|
||||
aCrear.push({ ...it, opp: o });
|
||||
}
|
||||
if (!aCrear.length) return { ok: false, error: "Ninguna actividad se puede crear: " + resultados.map((r) => r.error).join(" ") };
|
||||
|
||||
const { existentes, bloques } = resumenExistentes(acts);
|
||||
const v = validar({ items: aCrear, dias, existentes, bloques, hoy, ahoraMin });
|
||||
if (!v.ok) {
|
||||
const detalle = aCrear.filter((i) => v.porItem[i.key]).map((i) => `${i.nombre || i.oppId}: ${v.porItem[i.key].join(" ")}`);
|
||||
return { ok: false, error: "No se creó nada. Revisa: " + detalle.join(" · ") };
|
||||
}
|
||||
|
||||
// Se crean de a 3 en paralelo; si una falla, las demás siguen y todo queda registrado.
|
||||
const quien = session.email;
|
||||
let i = 0;
|
||||
const hechos = [];
|
||||
const trabajador = async () => {
|
||||
while (i < aCrear.length) {
|
||||
const it = aCrear[i++];
|
||||
try {
|
||||
const id = await crearActividad(token, it, it.opp, ownerId, objetivos.get(it.objetivo), quien);
|
||||
hechos.push({ oppId: it.oppId, nombre: it.nombre, cliente: it.cliente, tipo: it.tipo, objetivo: it.objetivo, dia: it.dia, hora: it.hora, estado: "creada", activityId: id });
|
||||
} catch (e) {
|
||||
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||||
hechos.push({ oppId: it.oppId, nombre: it.nombre, cliente: it.cliente, tipo: it.tipo, objetivo: it.objetivo, dia: it.dia, hora: it.hora, estado: "error", error: String(e?.message || e).slice(0, 200) });
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all([trabajador(), trabajador(), trabajador()]);
|
||||
|
||||
const todos = [...hechos, ...resultados.map((r) => ({ oppId: r.oppId, nombre: r.nombre, tipo: r.tipo, estado: r.estado, error: r.error }))];
|
||||
const loteId = guardarLote({ creadoPor: quien, ownerId, ownerEmail: owner, ownerName, desde: rango.desde, hasta: rango.hasta, items: todos });
|
||||
refrescar();
|
||||
return {
|
||||
ok: true,
|
||||
loteId,
|
||||
creadas: hechos.filter((h) => h.estado === "creada").length,
|
||||
errores: hechos.filter((h) => h.estado === "error").length,
|
||||
omitidas: resultados.length,
|
||||
resultados: todos,
|
||||
};
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e) };
|
||||
}
|
||||
}
|
||||
|
||||
// «Deshacer» una tanda: cancela (nunca borra) lo que siga abierto. Lo ya completado o cancelado no se toca.
|
||||
export async function deshacerLoteAction(loteId) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
const lote = getLote(Number(loteId));
|
||||
if (!lote) return { ok: false, error: "No encontré esa tanda." };
|
||||
if (lote.deshecho_en) return { ok: false, error: "Esa tanda ya se deshizo." };
|
||||
if (!(puedeAgendarPara(session, lote.owner_email) || session.email === lote.creado_por)) {
|
||||
return { ok: false, error: "No tienes permiso para deshacer esta tanda." };
|
||||
}
|
||||
try {
|
||||
const resumen = { canceladas: 0, yaCerradas: 0, errores: 0 };
|
||||
for (const it of lote.items) {
|
||||
if (it.estado !== "creada" || !it.activityId) continue;
|
||||
try {
|
||||
const r = await cancelarActividad(session.accessToken, it.tipo, it.activityId);
|
||||
if (r === "cancelada") resumen.canceladas++;
|
||||
else resumen.yaCerradas++;
|
||||
} catch (e) {
|
||||
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||||
resumen.errores++;
|
||||
}
|
||||
}
|
||||
marcarDeshecho(lote.id, session.email, resumen);
|
||||
refrescar();
|
||||
return { ok: true, ...resumen };
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e) };
|
||||
}
|
||||
}
|
||||
4
app/actividades/loading.js
Normal file
4
app/actividades/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
325
app/actividades/page.js
Normal file
325
app/actividades/page.js
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
import { Suspense } from "react";
|
||||
import Link from "next/link";
|
||||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter, puedeAgendarPara } from "../lib/authz";
|
||||
import { getActividades, getSystemUsers, getOportunidadesSemana, resolveOwnerId } from "../lib/queries";
|
||||
import { AGENDADOR, resumenExistentes, localDeIso } from "../lib/agendador";
|
||||
import { getLotesSemana } from "../lib/agendadorLotes";
|
||||
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import {
|
||||
armarPlanPeriodo, sinActividadPeriodo, hoyManagua, addDays, semanaDe, diasDelRango, esHabil, diaDe, diaCorto, diaSemana,
|
||||
PERIODOS_ACT, periodoActActivo, rangoPeriodoAct, SECCIONES, objetivoSugerido, COD_RENOVACION,
|
||||
} from "../lib/plan";
|
||||
import { actEstadoFinal } from "../lib/derive";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import PeriodoControles from "../components/plan/PeriodoControles";
|
||||
import PlanSeccion from "../components/plan/PlanSeccion";
|
||||
import MrrSegmentos from "../components/plan/MrrSegmentos";
|
||||
import SinActividadPanel from "../components/plan/SinActividadPanel";
|
||||
import AgendadorPanel from "../components/plan/AgendadorPanel";
|
||||
import DetalleActividades from "../components/plan/DetalleActividades";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
||||
const fechaCorta = (iso) => iso.split("-").reverse().slice(0, 2).join("/");
|
||||
const pct = (hechas, total) => (total ? Math.round((hechas / total) * 1000) / 10 : null);
|
||||
const pctTxt = (v) => (v == null ? "—" : `${v.toFixed(1)}%`);
|
||||
|
||||
// Franja de cobertura: una ficha por día (semana) o por semana (mes). Los días hábiles sin ninguna
|
||||
// actividad se resaltan como hueco; en la semana cada ficha abre el Plan del Día de ese día.
|
||||
function Franja({ rango, plan, hoy, owner }) {
|
||||
if (rango.tipo === "semana") {
|
||||
const dias = diasDelRango(rango.desde, rango.hasta).filter((d) => esHabil(d) || plan.porDia[d]);
|
||||
return (
|
||||
<div className="pa-franja">
|
||||
{dias.map((d) => {
|
||||
const x = plan.porDia[d];
|
||||
const hueco = esHabil(d) && !x;
|
||||
const futuro = d > hoy;
|
||||
const cls = `pa-dia${d === hoy ? " hoy" : ""}${futuro ? " futuro" : ""}${hueco ? " hueco" : ""}${esHabil(d) ? "" : " fin"}`;
|
||||
const texto = hueco
|
||||
? "sin actividades"
|
||||
: d <= hoy
|
||||
? `${x.hechas} de ${x.total} completadas`
|
||||
: `${x.total} agendada${x.total === 1 ? "" : "s"}`;
|
||||
const contenido = (
|
||||
<>
|
||||
<span className="t">{diaSemana(d)} {Number(d.slice(8, 10))}</span>
|
||||
<span className="s">{texto}</span>
|
||||
</>
|
||||
);
|
||||
const p = new URLSearchParams();
|
||||
if (owner) p.set("owner", owner);
|
||||
if (d !== hoy) p.set("fecha", d);
|
||||
const href = `/plan${p.toString() ? `?${p.toString()}` : ""}`;
|
||||
return (
|
||||
<Link key={d} href={href} className={cls} title="Abrir el Plan del Día de este día">
|
||||
{contenido}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Mes: una ficha por semana comercial (lunes–domingo) que toca el mes.
|
||||
const semanas = [];
|
||||
for (let l = semanaDe(rango.desde).lunes; l <= rango.hasta; l = addDays(l, 7)) semanas.push(l);
|
||||
return (
|
||||
<div className="pa-franja">
|
||||
{semanas.map((l) => {
|
||||
const dias = diasDelRango(l, addDays(l, 6)).filter((d) => d >= rango.desde && d <= rango.hasta);
|
||||
const total = dias.reduce((t, d) => t + (plan.porDia[d]?.total || 0), 0);
|
||||
const hechas = dias.reduce((t, d) => t + (plan.porDia[d]?.hechas || 0), 0);
|
||||
const sinAct = dias.filter((d) => esHabil(d) && !plan.porDia[d]).length;
|
||||
const fin = addDays(l, 6);
|
||||
const futura = l > hoy;
|
||||
const actual = l <= hoy && hoy <= fin;
|
||||
return (
|
||||
<div key={l} className={`pa-dia${actual ? " hoy" : ""}${futura ? " futuro" : ""}${total === 0 ? " hueco" : ""}`}>
|
||||
<span className="t">{fechaCorta(dias[0])} – {fechaCorta(dias[dias.length - 1])}</span>
|
||||
<span className="s">
|
||||
{total === 0 ? "sin actividades" : futura ? `${total} agendadas` : `${hechas} de ${total} completadas`}
|
||||
</span>
|
||||
{total > 0 && sinAct > 0 && <span className="s mal">{sinAct} día{sinAct === 1 ? "" : "s"} sin actividad</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ResumenEquipoPeriodo({ nombres, plan, rango, hoy, etiqueta }) {
|
||||
const semanasMes = [];
|
||||
if (rango.tipo === "mes") for (let l = semanaDe(rango.desde).lunes; l <= rango.hasta; l = addDays(l, 7)) semanasMes.push(l);
|
||||
const diasSemana = rango.tipo === "semana" ? diasDelRango(rango.desde, rango.hasta).filter(esHabil) : [];
|
||||
const filas = nombres.map((n) => ({ n, o: plan.porOwner[n] || { total: 0, hechas: 0, debidas: 0, debidasHechas: 0, vencidas: 0, porDia: {} } }));
|
||||
const sumaDia = (fn) => filas.reduce((t, f) => t + fn(f.o), 0);
|
||||
const tot = {
|
||||
total: sumaDia((o) => o.total), hechas: sumaDia((o) => o.hechas), debidas: sumaDia((o) => o.debidas),
|
||||
debidasHechas: sumaDia((o) => o.debidasHechas), vencidas: sumaDia((o) => o.vencidas),
|
||||
};
|
||||
const enSemana = (o, l) => diasDelRango(l, addDays(l, 6)).filter((d) => d >= rango.desde && d <= rango.hasta).reduce((t, d) => t + (o.porDia[d] || 0), 0);
|
||||
return (
|
||||
<section className="plan-equipo">
|
||||
<h1 className="plan-titulo plan-titulo-eq">PLAN DE ACTIVIDADES — RESUMEN DEL EQUIPO</h1>
|
||||
<div className="plan-meta"><span><strong>Período:</strong> {etiqueta}</span></div>
|
||||
<div className="ts">
|
||||
<table className="plan-eq-tbl pa-eq-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th>
|
||||
<th className="num">Agendadas</th>
|
||||
<th className="num">Completadas</th>
|
||||
<th className="num">Cumpl. a la fecha</th>
|
||||
<th className="num">Vencidas</th>
|
||||
{diasSemana.map((d) => <th key={d} className="num">{diaCorto(d)}</th>)}
|
||||
{semanasMes.map((l) => (
|
||||
<th key={l} className="num">
|
||||
{fechaCorta(l < rango.desde ? rango.desde : l)} – {fechaCorta(addDays(l, 6) > rango.hasta ? rango.hasta : addDays(l, 6))}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filas.map(({ n, o }) => (
|
||||
<tr key={n}>
|
||||
<td>{n}</td>
|
||||
<td className="num">{o.total}</td>
|
||||
<td className="num">{o.hechas}</td>
|
||||
<td className="num">{o.debidas ? `${pctTxt(pct(o.debidasHechas, o.debidas))} (${o.debidasHechas}/${o.debidas})` : "—"}</td>
|
||||
<td className={`num${o.vencidas ? " mal" : ""}`}>{o.vencidas}</td>
|
||||
{diasSemana.map((d) => {
|
||||
const c = o.porDia[d] || 0;
|
||||
return <td key={d} className={`num${c ? "" : " mal"}`}>{c || "○"}</td>;
|
||||
})}
|
||||
{semanasMes.map((l) => {
|
||||
const c = enSemana(o, l);
|
||||
return <td key={l} className={`num${c ? "" : " mal"}`}>{c || "○"}</td>;
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td><strong>Total equipo</strong></td>
|
||||
<td className="num"><strong>{tot.total}</strong></td>
|
||||
<td className="num"><strong>{tot.hechas}</strong></td>
|
||||
<td className="num"><strong>{tot.debidas ? `${pctTxt(pct(tot.debidasHechas, tot.debidas))} (${tot.debidasHechas}/${tot.debidas})` : "—"}</strong></td>
|
||||
<td className="num"><strong>{tot.vencidas}</strong></td>
|
||||
{diasSemana.map((d) => <td key={d} className="num"><strong>{plan.porDia[d]?.total || 0}</strong></td>)}
|
||||
{semanasMes.map((l) => <td key={l} className="num"><strong>{filas.reduce((t, f) => t + enSemana(f.o, l), 0)}</strong></td>)}
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<p className="hint plan-eq-nota">
|
||||
Actividades agendadas en actividades comerciales (oportunidades, casos y cuentas). ○ = ninguna actividad ese día o semana.
|
||||
Cumplimiento a la fecha = completadas ÷ actividades de los días anteriores a hoy ({fechaTxt(hoy)}); el avance de hoy está en el Plan del Día.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function PlanDeActividades({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const scope = ownerFilter(session, sp.owner, { asistente: true });
|
||||
const hoy = hoyManagua();
|
||||
const periodo = periodoActActivo(sp.periodo);
|
||||
const rango = rangoPeriodoAct(periodo, hoy);
|
||||
const { desde, hasta } = rango;
|
||||
const etiquetaPeriodo = PERIODOS_ACT.find((p) => p.k === periodo).lbl;
|
||||
const etiqueta = `${etiquetaPeriodo} · ${fechaTxt(desde)} – ${fechaTxt(hasta)}`;
|
||||
const esActualOFuturo = hasta >= hoy;
|
||||
|
||||
let raw, allUsers, oppsPeriodo;
|
||||
try {
|
||||
[raw, allUsers, oppsPeriodo] = await Promise.all([
|
||||
getActividades(session.accessToken, scope),
|
||||
session.isAdmin || scope.asistente ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
esActualOFuturo ? getOportunidadesSemana(session.accessToken, scope, desde, hasta) : Promise.resolve([]),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
// La asistente solo ve a los ejecutivos del piloto (ver ownerFilter).
|
||||
const owners = allUsers
|
||||
.filter((u) => EJECUTIVOS_VENTA.includes(u.name))
|
||||
.filter((u) => !scope.asistente || AGENDADOR.piloto.includes(u.email));
|
||||
const plan = armarPlanPeriodo(raw, desde, hasta, hoy);
|
||||
const r = plan.resumen;
|
||||
|
||||
const sinActividad = esActualOFuturo
|
||||
? sinActividadPeriodo(
|
||||
scope.emails?.length ? oppsPeriodo : oppsPeriodo.filter((o) => EJECUTIVOS_VENTA.includes(o.owner)),
|
||||
raw,
|
||||
desde,
|
||||
hasta
|
||||
)
|
||||
: [];
|
||||
|
||||
// Detalle: todas las actividades no canceladas del período (cualquier referente).
|
||||
const detalle = raw
|
||||
.filter((a) => a.estado !== "cancelada")
|
||||
.map((a) => ({ ...a, fecha: diaDe(a), estadoFinal: actEstadoFinal(a) }))
|
||||
.filter((a) => a.fecha && a.fecha >= desde && a.fecha <= hasta);
|
||||
|
||||
const quien = scope.locked
|
||||
? session.email
|
||||
: scope.emails.length === 1
|
||||
? owners.find((o) => o.email === scope.emails[0])?.name || scope.emails[0]
|
||||
: scope.emails.length
|
||||
? `${scope.emails.length} ejecutivos`
|
||||
: "Equipo";
|
||||
const verEquipo = !scope.locked && scope.emails.length !== 1 && owners.length > 0;
|
||||
const nombresEquipo = owners.filter((o) => !scope.emails.length || scope.emails.includes(o.email)).map((o) => o.name);
|
||||
const pctF = r.pctFecha;
|
||||
|
||||
// Agendador (piloto): solo en una semana actual o futura, con UN ejecutivo del piloto elegido, y para
|
||||
// quien tenga permiso (administrador, asistente o el propio ejecutivo). Ver lib/agendador.js.
|
||||
const ownerAgenda = scope.emails.length === 1 ? scope.emails[0] : null;
|
||||
let agendador = null;
|
||||
if (esActualOFuturo && rango.tipo === "semana" && ownerAgenda && puedeAgendarPara(session, ownerAgenda)) {
|
||||
let lotes = [];
|
||||
try {
|
||||
const ownerId = await resolveOwnerId(ownerAgenda, session.accessToken);
|
||||
lotes = ownerId ? getLotesSemana(ownerId, desde, hasta) : [];
|
||||
} catch { /* sin historial de tandas: el agendador funciona igual */ }
|
||||
const { existentes, bloques } = resumenExistentes(raw);
|
||||
agendador = {
|
||||
ownerEmail: ownerAgenda,
|
||||
ownerName: allUsers.find((u) => u.email === ownerAgenda)?.name || session.user?.name || ownerAgenda,
|
||||
periodo,
|
||||
dias: diasDelRango(desde > hoy ? desde : hoy, hasta).filter(esHabil),
|
||||
hoy,
|
||||
ahoraMin: localDeIso(new Date().toISOString()).min,
|
||||
candidatos: sinActividad.map((o) => ({
|
||||
id: o.id, nombre: o.nombre, cliente: o.cliente, valor: o.valor, pct: o.pct,
|
||||
tipoCodigo: o.tipoCodigo, esRenovacion: COD_RENOVACION.has(o.tipoCodigo), objetivoSugerido: objetivoSugerido(o),
|
||||
})),
|
||||
existentes,
|
||||
bloques,
|
||||
lotes,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Plan de Actividades</h2>
|
||||
<div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
</div>
|
||||
<Suspense fallback={null}>
|
||||
<div style={{ margin: "12px 0 16px" }}>
|
||||
<PeriodoControles
|
||||
periodos={PERIODOS_ACT}
|
||||
periodo={periodo}
|
||||
defecto="semana"
|
||||
tituloPdf={`Plan de actividades – ${quien} – ${etiquetaPeriodo} ${desde}`}
|
||||
tituloPdfEquipo={`Plan de actividades – Resumen del equipo – ${etiquetaPeriodo} ${desde}`}
|
||||
conEquipo={verEquipo}
|
||||
/>
|
||||
</div>
|
||||
</Suspense>
|
||||
|
||||
{verEquipo && <ResumenEquipoPeriodo nombres={nombresEquipo} plan={plan} rango={rango} hoy={hoy} etiqueta={etiqueta} />}
|
||||
|
||||
<div className="plan-doc plan-detalle">
|
||||
<h1 className="plan-titulo">PLAN DE ACTIVIDADES</h1>
|
||||
<div className="plan-meta">
|
||||
<span><strong>Período:</strong> {etiqueta}</span>
|
||||
<span><strong>Ejecutivo:</strong> {quien}</span>
|
||||
</div>
|
||||
|
||||
<div className="kpis plan-kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{pctTxt(pctF)}</span>
|
||||
<span className="l">
|
||||
{r.debidas ? `Cumplimiento a la fecha (${r.debidasHechas} de ${r.debidas} de los días anteriores a hoy)` : "Cumplimiento a la fecha: aún no hay días anteriores a hoy en el período"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{r.agendadas}</span>
|
||||
<span className="l">Actividades agendadas en el período ({r.hechas} completadas)</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={`n${r.vencidas ? " pierde" : ""}`}>{r.vencidas}</span>
|
||||
<span className="l">Vencidas (siguen abiertas y su día ya pasó)</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={`n${r.diasSinActividad ? " pierde" : ""}`}>{r.diasSinActividad}</span>
|
||||
<span className="l">Días hábiles sin actividad (de {r.diasHabiles})</span>
|
||||
</div>
|
||||
<MrrSegmentos secciones={plan.secciones} nota="oportunidades con actividad en el período" />
|
||||
</div>
|
||||
|
||||
<Franja rango={rango} plan={plan} hoy={hoy} owner={sp.owner} />
|
||||
|
||||
{plan.secciones.map((s) => (
|
||||
<PlanSeccion key={s.key} seccion={s} periodo />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{agendador && <AgendadorPanel {...agendador} />}
|
||||
|
||||
{esActualOFuturo && (
|
||||
<SinActividadPanel
|
||||
filas={sinActividad}
|
||||
titulo="Oportunidades por planificar: cierre estimado en el período y sin actividad agendada"
|
||||
hint={`Cierre estimado entre el ${fechaTxt(desde)} y el ${fechaTxt(hasta)} · ordenadas por prioridad (primero las de forecast 80% y 90%, luego por valor) · solo en pantalla, no va en el PDF`}
|
||||
vacio="Todas las oportunidades con cierre en este período tienen al menos una actividad agendada."
|
||||
nota="Cómo se lee esta lista: cuenta cualquier actividad del período (pendiente o ya completada) como planificada; solo se excluyen las canceladas. Por eso una oportunidad cuya llamada ya se completó no aparece aquí aunque no tenga un próximo paso. Para ver qué oportunidades no tienen un próximo paso pendiente, usa la columna «Agenda» en Previsión de Ventas."
|
||||
/>
|
||||
)}
|
||||
|
||||
<DetalleActividades actividades={detalle} locked={scope.locked} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
100
app/admin/metas/page.js
Normal file
100
app/admin/metas/page.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "../../lib/auth";
|
||||
import { getSystemUsers } from "../../lib/queries";
|
||||
import { getMetas, getMetaGlobal, setMeta, setMetaGlobal } from "../../lib/metas";
|
||||
import { EJECUTIVOS_VENTA } from "../../lib/derive";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminMetasPage() {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
if (!session.isAdmin) {
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Metas</h2>
|
||||
<p>Esta página es solo para administradores.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const allUsers = await getSystemUsers(session.accessToken);
|
||||
const metas = getMetas();
|
||||
const metaGlobal = getMetaGlobal();
|
||||
|
||||
const vendedoras = EJECUTIVOS_VENTA.map((nombre) => {
|
||||
const u = allUsers.find((x) => x.name === nombre);
|
||||
return { nombre, email: u?.email || null, monto: u ? metas[u.email] || 0 : 0 };
|
||||
});
|
||||
|
||||
async function guardarMeta(formData) {
|
||||
"use server";
|
||||
const email = formData.get("email");
|
||||
const monto = Number(formData.get("monto"));
|
||||
if (email && monto >= 0) setMeta(email, monto);
|
||||
revalidatePath("/admin/metas");
|
||||
revalidatePath("/");
|
||||
revalidatePath("/ganadas");
|
||||
revalidatePath("/prevision");
|
||||
revalidatePath("/tendencia");
|
||||
}
|
||||
|
||||
async function guardarGlobal(formData) {
|
||||
"use server";
|
||||
const monto = Number(formData.get("metaGlobal"));
|
||||
if (monto >= 0) setMetaGlobal(monto);
|
||||
revalidatePath("/admin/metas");
|
||||
revalidatePath("/");
|
||||
revalidatePath("/ganadas");
|
||||
revalidatePath("/prevision");
|
||||
revalidatePath("/tendencia");
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Metas mensuales</h2>
|
||||
<p className="hint">
|
||||
Solo administradores.</p>
|
||||
|
||||
<div className="panel" style={{ maxWidth: 420 }}>
|
||||
<h3>Meta global del equipo</h3>
|
||||
<form action={guardarGlobal} style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||
<input name="metaGlobal" type="number" step="1" min="0" defaultValue={metaGlobal} style={{ width: 120 }} />
|
||||
<button type="submit" className="login-btn">
|
||||
Guardar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ marginTop: 16, maxWidth: 520 }}>
|
||||
<h3>Meta por ejecutiva</h3>
|
||||
{vendedoras.map((v) => (
|
||||
<div
|
||||
key={v.nombre}
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: 8,
|
||||
alignItems: "center",
|
||||
padding: "8px 0",
|
||||
borderBottom: "1px solid var(--linea)",
|
||||
}}
|
||||
>
|
||||
<span style={{ width: 220, flexShrink: 0 }}>{v.nombre}</span>
|
||||
{v.email ? (
|
||||
<form action={guardarMeta} style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||
<input type="hidden" name="email" value={v.email} />
|
||||
<input name="monto" type="number" step="1" min="0" defaultValue={v.monto} style={{ width: 100 }} />
|
||||
<button type="submit" className="login-btn">
|
||||
Guardar
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<span style={{ color: "var(--pierde)" }}>No encontrada en systemusers</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
app/agenda/page.js
Normal file
10
app/agenda/page.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { redirect } from "next/navigation";
|
||||
|
||||
// Agenda pasó a ser la página de inicio ("/") — Marco pidió que sea lo primero que ve el equipo al
|
||||
// entrar, en vez de Ventas Resumen. Esta ruta se conserva como redirect por si algún bookmark viejo
|
||||
// apunta acá.
|
||||
export default async function AgendaRedirect({ searchParams }) {
|
||||
const params = new URLSearchParams(await searchParams);
|
||||
const qs = params.toString();
|
||||
redirect(qs ? `/?${qs}` : "/");
|
||||
}
|
||||
2
app/api/auth/[...nextauth]/route.js
Normal file
2
app/api/auth/[...nextauth]/route.js
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { handlers } from "../../../lib/auth";
|
||||
export const { GET, POST } = handlers;
|
||||
131
app/components/AppShell.js
Normal file
131
app/components/AppShell.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"use client";
|
||||
import { Suspense, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
|
||||
// El filtro de Propietario (`owner` en la URL) tiene que sobrevivir al cambio de página: cada
|
||||
// enlace del menú lo arrastra. Va dentro de un Suspense porque useSearchParams() así lo exige en
|
||||
// el layout; mientras resuelve, el enlace funciona igual (sin el filtro).
|
||||
function NavLink({ href, children, ...rest }) {
|
||||
const owner = useSearchParams().get("owner");
|
||||
return (
|
||||
<Link href={owner ? `${href}?owner=${encodeURIComponent(owner)}` : href} {...rest}>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function OwnerAwareLink({ href, children, ...rest }) {
|
||||
return (
|
||||
<Suspense
|
||||
fallback={
|
||||
<Link href={href} {...rest}>
|
||||
{children}
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<NavLink href={href} {...rest}>
|
||||
{children}
|
||||
</NavLink>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
// Hora de Nicaragua explícita: el servidor puede correr en otro huso horario y "en vivo" sin hora
|
||||
// no prueba nada — mostrar solo la hora local del navegador sería ambiguo sobre cuál huso es.
|
||||
function horaNicaragua(iso) {
|
||||
return new Intl.DateTimeFormat("es-NI", {
|
||||
timeZone: "America/Managua",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
}).format(new Date(iso));
|
||||
}
|
||||
|
||||
export default function AppShell({ pages, session, onSignIn, onSignOut, generatedAt, children }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const pathname = usePathname();
|
||||
const grupos = [...new Set(pages.map((p) => p.grupo))];
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<aside className={`side${open ? " open" : ""}`}>
|
||||
<OwnerAwareLink href="/" className="side-logo" style={{ display: "block" }}>
|
||||
<Image src="/assets/img/logo-alfa-blanco.png" alt="ALFA+" width={100} height={27} />
|
||||
<div className="sub">Analítica Comercial</div>
|
||||
</OwnerAwareLink>
|
||||
<nav className="nav">
|
||||
{grupos.map((g) => (
|
||||
<div key={g}>
|
||||
<div className="nav-grupo">{g}</div>
|
||||
{pages
|
||||
.filter((p) => p.grupo === g)
|
||||
.map((p) =>
|
||||
p.built ? (
|
||||
<OwnerAwareLink
|
||||
key={p.href}
|
||||
href={p.href}
|
||||
className={`nav-item${pathname === p.href ? " active" : ""}`}
|
||||
style={{ textDecoration: "none" }}
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
<span className="ico">{p.ico}</span>
|
||||
{p.label}
|
||||
</OwnerAwareLink>
|
||||
) : (
|
||||
<div key={p.href} className="nav-item soon" title="Próximamente">
|
||||
<span className="ico">{p.ico}</span>
|
||||
{p.label}
|
||||
<span className="tag">Pronto</span>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
<div className="side-foot">
|
||||
Datos: Dynamics 365
|
||||
<br />
|
||||
En vivo · act. {horaNicaragua(generatedAt)}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div className={`backdrop${open ? " open" : ""}`} onClick={() => setOpen(false)} />
|
||||
|
||||
<div className="main">
|
||||
<div className="topbar">
|
||||
<button className="hamburger" aria-label="Menú" onClick={() => setOpen((o) => !o)} type="button">
|
||||
☰
|
||||
</button>
|
||||
<div className="ctrl" style={{ marginLeft: "auto" }}>
|
||||
{session?.email ? (
|
||||
<>
|
||||
{session.isAdmin && (
|
||||
<Link href="/admin/metas" style={{ marginRight: 12, fontSize: 13, color: "var(--marca)" }}>
|
||||
⚙ Metas
|
||||
</Link>
|
||||
)}
|
||||
<span style={{ marginRight: 12 }}>
|
||||
{session.email} {session.isAdmin ? "(admin)" : ""}
|
||||
</span>
|
||||
<form action={onSignOut}>
|
||||
<button type="submit" className="login-btn">
|
||||
Cerrar sesión
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
) : (
|
||||
<form action={onSignIn}>
|
||||
<button type="submit" className="login-btn">
|
||||
Iniciar sesión
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<main className="content">{children}</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
app/components/ErrorNotice.js
Normal file
17
app/components/ErrorNotice.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
export default function ErrorNotice({ error }) {
|
||||
const isExpired = error?.message === "TOKEN_EXPIRED" || error?.message?.includes("RefreshFailed");
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>No se pudo cargar la información</h2>
|
||||
{isExpired ? (
|
||||
<p>Tu sesión con Dynamics expiró. Cerrá sesión y volvé a iniciarla.</p>
|
||||
) : (
|
||||
<p>
|
||||
Dynamics no respondió correctamente (posiblemente por límite de consultas). Recargá la página en unos
|
||||
segundos.
|
||||
</p>
|
||||
)}
|
||||
<p style={{ color: "#9db4c9", fontSize: 12 }}>{error?.message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
app/components/FilterChips.js
Normal file
44
app/components/FilterChips.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use client";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
import { parseFiltParam, encodeFiltParam } from "../lib/filterState";
|
||||
|
||||
// Chips de filtros activos — equivalente a chips()/bindChips() del sitio HTML (assets/js/filters.js).
|
||||
// dimLabels: {dimKey: "Etiqueta legible"} opcional, para no mostrar la clave técnica cruda.
|
||||
export default function FilterChips({ dimLabels = {} }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const filt = parseFiltParam(searchParams.get("f"));
|
||||
const keys = Object.keys(filt);
|
||||
if (!keys.length) return null;
|
||||
|
||||
function removeDim(dim) {
|
||||
const next = { ...filt };
|
||||
delete next[dim];
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
const f = encodeFiltParam(next);
|
||||
if (f) params.set("f", f);
|
||||
else params.delete("f");
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete("f");
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="chips">
|
||||
<span className="lbl">Filtros:</span>
|
||||
{keys.map((k) => (
|
||||
<span key={k} className="chip" onClick={() => removeDim(k)} title="Quitar filtro">
|
||||
{dimLabels[k] || k}: {filt[k]} ✕
|
||||
</span>
|
||||
))}
|
||||
<span className="chip clear" onClick={clearAll}>Limpiar</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
31
app/components/FilterableRow.js
Normal file
31
app/components/FilterableRow.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use client";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
import { parseFiltParam, encodeFiltParam, toggleFilt, isFiltActive } from "../lib/filterState";
|
||||
|
||||
// Envoltura clickeable genérica para clic-para-filtrar — reemplaza bindRows()/bindMatriz*() del
|
||||
// sitio HTML (assets/js/filters.js). `pairs` es [[dim, valor], ...]: una fila de panel manda un
|
||||
// solo par, una celda de matriz (calidad×movimiento, plan×termómetro) manda dos — el toggle es
|
||||
// "todo o nada" sobre ese conjunto de ejes (ver toggleFilt en lib/filterState.js).
|
||||
export default function FilterableRow({ pairs, className = "", activeClassName = "active", as: As = "div", children, ...rest }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const filt = parseFiltParam(searchParams.get("f"));
|
||||
const active = isFiltActive(filt, pairs);
|
||||
|
||||
function onClick() {
|
||||
const next = toggleFilt(filt, pairs);
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
const f = encodeFiltParam(next);
|
||||
if (f) params.set("f", f);
|
||||
else params.delete("f");
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
return (
|
||||
<As className={`${className} ${active ? activeClassName : ""}`.trim()} onClick={onClick} {...rest}>
|
||||
{children}
|
||||
</As>
|
||||
);
|
||||
}
|
||||
8
app/components/LoginPrompt.js
Normal file
8
app/components/LoginPrompt.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export default function LoginPrompt() {
|
||||
return (
|
||||
<div style={{ padding: 40, textAlign: "center" }}>
|
||||
<h2>Informe Comercial ALFA+</h2>
|
||||
<p>Iniciá sesión con tu cuenta de Alfanumeric para ver tu información.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
168
app/components/OwnerControl.js
Normal file
168
app/components/OwnerControl.js
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
"use client";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
|
||||
// Selector de Propietario con multi-selección — puerto de owner.js/owner-panel (App Informe).
|
||||
// Estado en la URL (`owner=email1,email2`), no en un Set en memoria de módulo como el HTML: cada
|
||||
// página server-side ya lee esa lista vía ownerFilter() (authz.js). Sin el param `owner` en la URL
|
||||
// = "todos" — pero en el dropdown eso se representa con el set COMPLETO marcado (no un set vacío):
|
||||
// así un clic sobre un ejecutivo ya marcado lo desmarca a él y deja a los demás como estaban, en
|
||||
// vez de invertir la selección entera (bug real encontrado al probar: con "vacío = todos", el
|
||||
// primer clic dejaba SOLO a esa persona marcada). No se puede llegar a 0 marcados: desmarcar el
|
||||
// último no hace nada, en vez de una pantalla en blanco confusa.
|
||||
//
|
||||
// Persistencia entre páginas: el menú lateral (AppShell) arrastra `owner` en cada enlace, y como
|
||||
// respaldo la última selección se guarda en localStorage — si se abre una página sin `owner` en la
|
||||
// URL (recarga, otra pestaña, enlace directo) se restaura. "*" = todos. Las páginas no comparten la
|
||||
// misma lista de propietarios (Tubería: equipo activo; Ganadas/Perdidas: histórico; Renovaciones:
|
||||
// Ventas + SAC), así que los correos que no existan en la lista de ESTA página se descartan.
|
||||
const STORAGE_KEY = "informe.owner";
|
||||
const readSaved = () => {
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const saveSel = (value) => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, value);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export default function OwnerControl({ owners, current, locked, lockedLabel }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef(null);
|
||||
const allRef = useRef(null);
|
||||
const currentKey = (current || []).join(",");
|
||||
const ownersKey = owners.map((o) => o.email).join(",");
|
||||
|
||||
const effectiveSet = (list) => {
|
||||
const arr = list && list.length ? list : owners.map((o) => o.email);
|
||||
return new Set(arr);
|
||||
};
|
||||
|
||||
// Estado local vía ref además de useState: dos clics seguidos en el dropdown ocurren en el mismo
|
||||
// tick de JS, antes de que React aplique el primer setState — computar `next` desde el ref (no
|
||||
// desde `selected`, el valor de render) evita perder el primer clic.
|
||||
const [selected, setSelected] = useState(() => effectiveSet(current));
|
||||
const selRef = useRef(selected);
|
||||
useEffect(() => {
|
||||
const next = effectiveSet(current);
|
||||
selRef.current = next;
|
||||
setSelected(next);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentKey]);
|
||||
|
||||
// Descarta de la URL los correos que no están en la lista de esta página y, si la URL no trae
|
||||
// `owner`, restaura la selección guardada (ver nota arriba). No corre para el vendedor (locked).
|
||||
useEffect(() => {
|
||||
if (locked) return;
|
||||
const valid = new Set(owners.map((o) => o.email.toLowerCase()));
|
||||
const cur = (current || []).map((e) => e.toLowerCase());
|
||||
let wanted = null;
|
||||
if (cur.length) {
|
||||
const kept = cur.filter((e) => valid.has(e));
|
||||
if (kept.length !== cur.length) wanted = kept;
|
||||
} else {
|
||||
const saved = readSaved();
|
||||
if (saved && saved !== "*") {
|
||||
const kept = saved.split(",").filter((e) => valid.has(e.toLowerCase()));
|
||||
if (kept.length && kept.length < valid.size) wanted = kept;
|
||||
}
|
||||
}
|
||||
if (wanted === null) return;
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (!wanted.length || wanted.length === valid.size) params.delete("owner");
|
||||
else params.set("owner", wanted.join(","));
|
||||
const qs = params.toString();
|
||||
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [currentKey, ownersKey, locked]);
|
||||
|
||||
// Estado intermedio de «Seleccionar todos» cuando hay una selección parcial.
|
||||
useEffect(() => {
|
||||
if (allRef.current) allRef.current.indeterminate = selected.size > 0 && selected.size < owners.length;
|
||||
}, [selected, owners.length]);
|
||||
|
||||
useEffect(() => {
|
||||
function onDocClick(e) {
|
||||
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
|
||||
}
|
||||
document.addEventListener("mousedown", onDocClick);
|
||||
return () => document.removeEventListener("mousedown", onDocClick);
|
||||
}, []);
|
||||
|
||||
if (locked) {
|
||||
return (
|
||||
<div className="ctrl owner-ctrl">
|
||||
<label>Propietario</label>
|
||||
<button type="button" className="owner-btn" disabled>
|
||||
{lockedLabel}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function applySet(nextSet) {
|
||||
selRef.current = nextSet;
|
||||
setSelected(nextSet);
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
const all = nextSet.size === 0 || nextSet.size === owners.length;
|
||||
if (all) params.delete("owner");
|
||||
else params.set("owner", [...nextSet].join(","));
|
||||
saveSel(all ? "*" : [...nextSet].join(","));
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
const allSelected = selected.size === owners.length;
|
||||
// Desmarcar «Seleccionar todos» no puede dejar 0 marcados (pantalla en blanco): deja solo al
|
||||
// primero de la lista, que el usuario ajusta marcando a los demás.
|
||||
function toggleAll() {
|
||||
if (allSelected) {
|
||||
if (owners.length) applySet(new Set([owners[0].email]));
|
||||
} else {
|
||||
applySet(new Set(owners.map((o) => o.email)));
|
||||
}
|
||||
}
|
||||
|
||||
function toggle(email) {
|
||||
const next = new Set(selRef.current);
|
||||
if (next.has(email)) next.delete(email);
|
||||
else next.add(email);
|
||||
if (next.size === 0) return; // no se puede desmarcar al último
|
||||
applySet(next);
|
||||
}
|
||||
|
||||
const label =
|
||||
selected.size === owners.length
|
||||
? "Todos los propietarios"
|
||||
: selected.size === 1
|
||||
? owners.find((o) => o.email === [...selected][0])?.name || [...selected][0]
|
||||
: `${selected.size} propietarios`;
|
||||
|
||||
return (
|
||||
<div className="ctrl owner-ctrl" ref={ref}>
|
||||
<label>Propietario</label>
|
||||
<button type="button" className="owner-btn" onClick={() => setOpen((o) => !o)}>
|
||||
{label}
|
||||
</button>
|
||||
<div className={`owner-panel${open ? " open" : ""}`}>
|
||||
<label className="owner-row owner-all">
|
||||
<input type="checkbox" ref={allRef} checked={allSelected} onChange={toggleAll} /> Seleccionar todos
|
||||
</label>
|
||||
{owners.map((o) => (
|
||||
<label className="owner-row" key={o.id}>
|
||||
<input type="checkbox" checked={selected.has(o.email)} onChange={() => toggle(o.email)} />
|
||||
{" "}
|
||||
{o.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
17
app/components/PageLoading.js
Normal file
17
app/components/PageLoading.js
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// Fallback de carga — Next.js la muestra automáticamente (vía loading.js) mientras la página de
|
||||
// datos espera Dynamics, en vez de dejar la pantalla en blanco. El armazón (nav, topbar) ya está
|
||||
// pintado en este punto porque vive en layout.js, fuera de este límite de Suspense.
|
||||
export default function PageLoading() {
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div className="kpis">
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<div className="kpi" key={i} style={{ opacity: 0.5 }}>
|
||||
<span className="n">···</span>
|
||||
<span className="l">Cargando…</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
24
app/components/PlanFilterSelect.js
Normal file
24
app/components/PlanFilterSelect.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use client";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
// Select "Plan de Cierre" de Detalle — navega por URL (?plan=...) al cambiar, mismo patrón que el
|
||||
// resto de la app (sin estado de cliente propio, todo vive en la URL).
|
||||
export default function PlanFilterSelect({ options, current, baseHref }) {
|
||||
const router = useRouter();
|
||||
return (
|
||||
<select
|
||||
value={current || ""}
|
||||
onChange={(e) => {
|
||||
const url = new URL(baseHref, "http://x");
|
||||
if (e.target.value) url.searchParams.set("plan", e.target.value);
|
||||
else url.searchParams.delete("plan");
|
||||
router.push(url.pathname + url.search);
|
||||
}}
|
||||
>
|
||||
<option value="">Todos los planes</option>
|
||||
{options.map((p) => (
|
||||
<option key={p} value={p}>{p}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
83
app/components/ReportModal.js
Normal file
83
app/components/ReportModal.js
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"use client";
|
||||
import { useState } from "react";
|
||||
|
||||
// Modal de informe imprimible — puerto de openReporteEjecutivo()/openInformePrevision() +
|
||||
// bindPrint() (App Informe/assets/js/modals.js, pdf.js). Sin librería de PDF: usa window.print()
|
||||
// + las reglas @media print de public/assets/css/layout.css sobre body.rep-print (ya existían,
|
||||
// vendorizadas junto con el resto del CSS del sitio HTML).
|
||||
export default function ReportModal({ buttonLabel, disabled, disabledTitle, children }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
function handlePrint() {
|
||||
document.body.classList.add("rep-print");
|
||||
const cleanup = () => {
|
||||
document.body.classList.remove("rep-print");
|
||||
window.removeEventListener("afterprint", cleanup);
|
||||
};
|
||||
window.addEventListener("afterprint", cleanup);
|
||||
window.print();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="rep-btn"
|
||||
onClick={() => setOpen(true)}
|
||||
disabled={disabled}
|
||||
title={disabled ? disabledTitle : undefined}
|
||||
>
|
||||
{buttonLabel}
|
||||
</button>
|
||||
{open && (
|
||||
<>
|
||||
<div
|
||||
id="repModalBd"
|
||||
style={{ display: "block", position: "fixed", inset: 0, background: "rgba(1,32,91,.55)", zIndex: 29 }}
|
||||
onClick={() => setOpen(false)}
|
||||
/>
|
||||
<div
|
||||
id="repModal"
|
||||
style={{
|
||||
display: "block", position: "fixed", top: "3%", left: "8%", right: "8%", bottom: "3%",
|
||||
background: "#fff", borderRadius: 12, zIndex: 30, boxShadow: "0 20px 60px rgba(1,32,91,.35)",
|
||||
padding: 0, overflow: "auto",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="rep-actions"
|
||||
style={{
|
||||
display: "flex", justifyContent: "flex-end", gap: 8, padding: "14px 20px",
|
||||
borderBottom: "1px solid var(--linea)", position: "sticky", top: 0, background: "#fff",
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePrint}
|
||||
style={{
|
||||
fontFamily: "var(--sans)", fontSize: 13, padding: "7px 14px", border: "1px solid var(--marca)",
|
||||
borderRadius: 6, background: "var(--marca)", color: "#fff", cursor: "pointer", fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
🖨 Imprimir
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
style={{
|
||||
fontFamily: "var(--sans)", fontSize: 13, padding: "7px 14px", border: "1px solid var(--linea)",
|
||||
borderRadius: 6, background: "#fff", cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
✕ Cerrar
|
||||
</button>
|
||||
</div>
|
||||
<div id="repModalBody" style={{ padding: "32px 40px" }}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
28
app/components/SegTabs.js
Normal file
28
app/components/SegTabs.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
"use client";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
|
||||
// Pestañas rotativas genéricas — reemplaza indTabsBar()/las pestañas de MTZ_DIMS/COH_DIMS del
|
||||
// sitio HTML (assets/js/tables.js). `tabs` es [{k, lbl}], `paramName` el searchParam que guarda la
|
||||
// pestaña activa (equivalente a indTab/mtzEjeDim/cohDim en state.js — acá vive en la URL, no en
|
||||
// una variable global de módulo).
|
||||
export default function SegTabs({ tabs, activeKey, paramName }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
function onClick(k) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.set(paramName, k);
|
||||
router.push(`${pathname}?${params.toString()}`, { scroll: false });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="seg-tabs">
|
||||
{tabs.map((t) => (
|
||||
<button key={t.k} type="button" className={t.k === activeKey ? "on" : ""} onClick={() => onClick(t.k)}>
|
||||
{t.lbl}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
247
app/components/agenda/AgendaClient.js
Normal file
247
app/components/agenda/AgendaClient.js
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
"use client";
|
||||
import { useState, useMemo } from "react";
|
||||
import { actAncla, actEstadoFinal } from "../../lib/derive";
|
||||
import { actividadUrl } from "../../lib/constants";
|
||||
|
||||
const AG_DIAS = ["Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"];
|
||||
const AG_MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||||
const AG_MESES_LARGO = [
|
||||
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
|
||||
];
|
||||
|
||||
const pad = (n) => (n < 10 ? "0" + n : "" + n);
|
||||
const iso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
const hoyISO = () => iso(new Date());
|
||||
// Semana Lunes-Domingo, igual que el resto del informe.
|
||||
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 fechaISO(a) {
|
||||
const f = actAncla(a);
|
||||
return f ? String(f).slice(0, 10) : null;
|
||||
}
|
||||
function diasParaVencer(a) {
|
||||
const f = fechaISO(a);
|
||||
if (!f) return null;
|
||||
const d = new Date(f + "T12:00:00");
|
||||
const hoy = new Date();
|
||||
hoy.setHours(12, 0, 0, 0);
|
||||
return Math.round((d - hoy) / 86400000);
|
||||
}
|
||||
function fechaTxt(f) {
|
||||
if (!f) return "—";
|
||||
const [y, m, d] = f.split("-");
|
||||
return `${d}/${m}/${y}`;
|
||||
}
|
||||
|
||||
function Item({ a }) {
|
||||
const venc = a.estadoFinal === "Vencida";
|
||||
const hecha = a.estadoFinal === "Completada";
|
||||
const ref = a.referente && a.referente.nombre ? a.referente.nombre : a.asunto || "—";
|
||||
const sub = [a.owner.split(" ").slice(0, 2).join(" ")];
|
||||
if (venc) sub.push(`vencida hace ${Math.abs(a.dv)} día${Math.abs(a.dv) === 1 ? "" : "s"}`);
|
||||
if (hecha) sub.push("completada");
|
||||
return (
|
||||
<a
|
||||
className={`ag-item t-${a.tipo.toLowerCase()}${venc ? " venc" : ""}${hecha ? " hecha" : ""}`}
|
||||
href={actividadUrl(a)}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
title={a.asunto || ""}
|
||||
>
|
||||
<span className="ag-item-t">{a.tipo} · {ref}</span>
|
||||
<span className="ag-item-s">{sub.join(" · ")}</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AgendaClient({ actividades }) {
|
||||
const [vista, setVista] = useState("semana");
|
||||
const [ancla, setAncla] = useState(() => new Date());
|
||||
const [tipos, setTipos] = useState(new Set(["Cita", "Llamada", "Tarea"]));
|
||||
const [verHechas, setVerHechas] = useState(false);
|
||||
const [diaSel, setDiaSel] = useState(null);
|
||||
|
||||
const list = useMemo(() => {
|
||||
return actividades
|
||||
.filter((a) => tipos.has(a.tipo) && a.estado !== "cancelada" && fechaISO(a))
|
||||
.map((a) => ({ ...a, fecha: fechaISO(a), dv: diasParaVencer(a), estadoFinal: actEstadoFinal(a) }))
|
||||
.filter((a) => verHechas || a.estadoFinal !== "Completada");
|
||||
}, [actividades, tipos, verHechas]);
|
||||
|
||||
const lunesHoy = inicioSemana(new Date());
|
||||
const domingoHoy = new Date(lunesHoy);
|
||||
domingoHoy.setDate(lunesHoy.getDate() + 6);
|
||||
const estaSem = list.filter((a) => a.fecha >= iso(lunesHoy) && a.fecha <= iso(domingoHoy)).length;
|
||||
const venc = list.filter((a) => a.estadoFinal === "Vencida").length;
|
||||
const pend = list.filter((a) => a.estadoFinal === "Pendiente").length;
|
||||
|
||||
const toggleTipo = (t) => {
|
||||
setTipos((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(t)) next.delete(t); else next.add(t);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const cursor = vista === "mes" ? new Date(ancla.getFullYear(), ancla.getMonth(), 1) : ancla;
|
||||
|
||||
const mover = (d) => {
|
||||
setDiaSel(null);
|
||||
setAncla((prev) => {
|
||||
const next = new Date(prev);
|
||||
if (vista === "semana") next.setDate(next.getDate() + d * 7);
|
||||
else next.setMonth(next.getMonth() + d);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
let cuerpo, lbl;
|
||||
if (vista === "semana") {
|
||||
const lunes = inicioSemana(cursor);
|
||||
const dias = Array.from({ length: 7 }, (_, i) => {
|
||||
const d = new Date(lunes);
|
||||
d.setDate(lunes.getDate() + i);
|
||||
return d;
|
||||
});
|
||||
lbl = `${dias[0].getDate()} ${AG_MESES[dias[0].getMonth()]} – ${dias[6].getDate()} ${AG_MESES[dias[6].getMonth()]} ${dias[6].getFullYear()}`;
|
||||
const hoy = hoyISO();
|
||||
cuerpo = (
|
||||
<div className="ag-week">
|
||||
{dias.map((d, i) => {
|
||||
const diso = iso(d);
|
||||
const items = list
|
||||
.filter((a) => a.fecha === diso)
|
||||
.sort((a, b) => (a.referente?.nombre || "").localeCompare(b.referente?.nombre || ""));
|
||||
return (
|
||||
<div className={`ag-day${diso === hoy ? " hoy" : ""}`} key={diso}>
|
||||
<div className="ag-day-h">
|
||||
<span>{AG_DIAS[i]}</span>
|
||||
<span>{d.getDate()} {AG_MESES[d.getMonth()]}</span>
|
||||
</div>
|
||||
{items.length ? items.map((a) => <Item a={a} key={a.id} />) : <span className="ag-vacio">Sin actividades</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
} else if (vista === "mes") {
|
||||
const inicio = inicioSemana(new Date(cursor.getFullYear(), cursor.getMonth(), 1));
|
||||
const celdas = Array.from({ length: 42 }, (_, i) => {
|
||||
const d = new Date(inicio);
|
||||
d.setDate(inicio.getDate() + i);
|
||||
return d;
|
||||
});
|
||||
const hoy = hoyISO();
|
||||
lbl = `${AG_MESES_LARGO[cursor.getMonth()]} ${cursor.getFullYear()}`;
|
||||
const sel = diaSel ? list.filter((a) => a.fecha === diaSel) : [];
|
||||
cuerpo = (
|
||||
<>
|
||||
<div className="ag-month">
|
||||
{AG_DIAS.map((n) => <div className="ag-m-h" key={n}>{n}</div>)}
|
||||
{celdas.map((d) => {
|
||||
const diso = iso(d);
|
||||
const items = list.filter((a) => a.fecha === diso);
|
||||
const hayVenc = items.some((a) => a.estadoFinal === "Vencida");
|
||||
return (
|
||||
<div
|
||||
className={`ag-m-d${d.getMonth() !== cursor.getMonth() ? " otro" : ""}${diso === hoy ? " hoy" : ""}${diso === diaSel ? " sel" : ""}`}
|
||||
key={diso}
|
||||
onClick={() => setDiaSel(diso === diaSel ? null : diso)}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<span className="ag-m-num">{d.getDate()}</span>
|
||||
{items.length > 0 && <span className={`ag-m-badge${hayVenc ? " venc" : ""}`}>{items.length}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{diaSel && (
|
||||
<div className="panel" style={{ marginTop: 14, marginBottom: 0 }}>
|
||||
<h3>{fechaTxt(diaSel)}</h3>
|
||||
{sel.length ? (
|
||||
<div className="ag-lista">{sel.map((a) => <Item a={a} key={a.id} />)}</div>
|
||||
) : (
|
||||
<p className="hint" style={{ margin: 0 }}>Sin actividades este día.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
const v = list.filter((a) => a.estadoFinal === "Vencida").sort((a, b) => a.dv - b.dv);
|
||||
const masViejo = v.length ? Math.abs(v[0].dv) : 0;
|
||||
lbl = `${v.length} vencida${v.length === 1 ? "" : "s"}`;
|
||||
cuerpo = (
|
||||
<div className="panel" style={{ marginBottom: 0 }}>
|
||||
<h3>Vencidas — de la más atrasada a la más reciente</h3>
|
||||
{v.length ? (
|
||||
<>
|
||||
<p className="hint">{v.length} actividades planificadas cuya fecha ya pasó y siguen abiertas · la más antigua lleva {masViejo} días</p>
|
||||
<div className="ag-lista scroll">{v.map((a) => <Item a={a} key={a.id} />)}</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="hint" style={{ margin: 0 }}>No hay actividades vencidas con este filtro.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="panel" style={{ display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap", padding: "12px 18px" }}>
|
||||
<div>
|
||||
<span className="ag-f-lbl">Tipo de actividad</span>
|
||||
<div className="ag-tipos">
|
||||
{["Cita", "Llamada", "Tarea"].map((t) => (
|
||||
<label className="ag-tipo" key={t}>
|
||||
<input type="checkbox" checked={tipos.has(t)} onChange={() => toggleTipo(t)} /> {t}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="ag-f-lbl">Estado</span>
|
||||
<div className="ag-tipos">
|
||||
<label className="ag-tipo">
|
||||
<input type="checkbox" checked={verHechas} onChange={(e) => setVerHechas(e.target.checked)} /> Mostrar completadas
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--tinta-suave)" }}>
|
||||
Se excluyen las canceladas
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{list.length}</span><span className="l">Actividades con el filtro actual</span></div>
|
||||
<div className="kpi"><span className="n">{estaSem}</span><span className="l">Esta semana (lun a dom)</span></div>
|
||||
<div className="kpi"><span className="n">{pend}</span><span className="l">Pendientes por delante</span></div>
|
||||
<div className="kpi"><span className="n pierde">{venc}</span><span className="l">Vencidas — su fecha ya pasó</span></div>
|
||||
</div>
|
||||
|
||||
<div className="ag-toolbar">
|
||||
<div className="seg-tabs">
|
||||
{[["semana", "Semana"], ["mes", "Mes"], ["vencidas", "Vencidas"]].map(([k, l]) => (
|
||||
<button key={k} className={vista === k ? "on" : ""} type="button" onClick={() => { setVista(k); setDiaSel(null); }}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{vista !== "vencidas" && (
|
||||
<div className="ag-nav">
|
||||
<button className="ag-nav-b" type="button" aria-label="Anterior" onClick={() => mover(-1)}>←</button>
|
||||
<span className="ag-nav-lbl">{lbl}</span>
|
||||
<button className="ag-nav-b" type="button" aria-label="Siguiente" onClick={() => mover(1)}>→</button>
|
||||
<button className="ag-nav-b" type="button" onClick={() => { setAncla(new Date()); setDiaSel(null); }}>Hoy</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{cuerpo}
|
||||
</>
|
||||
);
|
||||
}
|
||||
94
app/components/nuevas/CohMatriz.js
Normal file
94
app/components/nuevas/CohMatriz.js
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import React from "react";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
import SegTabs from "../SegTabs";
|
||||
|
||||
// Matriz de calor dimensión × mes de creación — puerto de cohMatriz()/cohHeat()
|
||||
// (App Informe/assets/js/pages/nuevas.js). `dims`/`metricas` traen `calc`/`fmt` (y `rgb` para el
|
||||
// color); el heat se computa acá mismo contra el máximo de la tabla completa.
|
||||
export default function CohMatriz({ arr, meses, dims, metricas, activeDimKey, activeMetKey, mesLbl }) {
|
||||
const dim = dims.find((d) => d.k === activeDimKey) || dims[0];
|
||||
const met = metricas.find((m) => m.k === activeMetKey) || metricas[0];
|
||||
|
||||
const cats = [...new Set(arr.map((o) => o[dim.k] || "(sin dato)"))]
|
||||
.map((k) => ({ k, n: arr.filter((o) => (o[dim.k] || "(sin dato)") === k).length }))
|
||||
.sort((a, b) => b.n - a.n)
|
||||
.slice(0, 14);
|
||||
const cel = (k, m) => arr.filter((o) => (o[dim.k] || "(sin dato)") === k && o.mesCohorte === m);
|
||||
const valores = cats.flatMap((c) => meses.map((m) => met.calc(cel(c.k, m)))).filter((v) => v != null);
|
||||
const max = Math.max(...valores, 0);
|
||||
|
||||
function heat(v) {
|
||||
if (v == null) return { bg: "", fg: "var(--tinta-suave)" };
|
||||
const r = max > 0 ? Math.max(0, v) / max : 0;
|
||||
const a = v === 0 ? 0 : 0.06 + 0.74 * r;
|
||||
return { bg: a ? `rgba(${met.rgb},${a.toFixed(2)})` : "", fg: a > 0.48 ? "#fff" : "var(--tinta)" };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>Matriz de Indicadores - {dim.lbl} × mes de creación</h3>
|
||||
<p className="hint">
|
||||
Clic en una fila o celda filtra · solo las 14 categorías con más volumen · ⚠ un 100% sobre 2 oportunidades pinta igual que sobre 40: pasa el cursor para ver el conteo real
|
||||
</p>
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<SegTabs tabs={dims.map((d) => ({ k: d.k, lbl: d.lbl }))} activeKey={dim.k} paramName="cohd" />
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={metricas.map((m) => ({ k: m.k, lbl: m.lbl }))} activeKey={met.k} paramName="cohm" />
|
||||
</div>
|
||||
<div
|
||||
className="mze"
|
||||
style={{ gridTemplateColumns: `minmax(130px,1.5fr) repeat(${meses.length},minmax(56px,1fr)) minmax(70px,.85fr)` }}
|
||||
>
|
||||
<div className="mze-h eje" />
|
||||
{meses.map((m) => <div className="mze-h" key={m}>{mesLbl(m).slice(0, 3)}</div>)}
|
||||
<div className="mze-h tot">Total</div>
|
||||
{cats.map((c) => {
|
||||
const totA = arr.filter((o) => (o[dim.k] || "(sin dato)") === c.k);
|
||||
return (
|
||||
<React.Fragment key={c.k}>
|
||||
<FilterableRow as="div" pairs={[[dim.k, c.k]]} className="mze-r" title={`Ver solo ${c.k}`}>
|
||||
{c.k}
|
||||
</FilterableRow>
|
||||
{meses.map((m) => {
|
||||
const a = cel(c.k, m);
|
||||
const v = met.calc(a);
|
||||
const h = heat(v);
|
||||
return (
|
||||
<FilterableRow
|
||||
as="div"
|
||||
key={`${c.k}-${m}`}
|
||||
pairs={[[dim.k, c.k], ["mesCohorte", m]]}
|
||||
className={`mze-c${a.length ? "" : " vacia"}`}
|
||||
style={{ background: h.bg, color: h.fg }}
|
||||
title={`${c.k} · ${mesLbl(m)} — ${a.length} creada(s), ${a.filter((o) => o.estado === "Ganada").length} ganada(s), ${a.filter((o) => o.estado === "Perdida").length} perdida(s), ${a.filter((o) => o.estado === "Abierta").length} abierta(s)`}
|
||||
>
|
||||
<span className="n">{met.fmt(v)}</span>
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
<div className="mze-c tot">
|
||||
<span className="n">{met.fmt(met.calc(totA))}</span>
|
||||
<span className="v">{totA.length} creadas</span>
|
||||
</div>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
<div className="mze-r tot">Total</div>
|
||||
{meses.map((m) => {
|
||||
const a = arr.filter((o) => o.mesCohorte === m);
|
||||
return (
|
||||
<div className="mze-c tot" key={`pie-${m}`}>
|
||||
<span className="n">{met.fmt(met.calc(a))}</span>
|
||||
<span className="v">{a.length}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="mze-c tot">
|
||||
<span className="n">{met.fmt(met.calc(arr))}</span>
|
||||
<span className="v">{arr.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
77
app/components/nuevas/MesesControl.js
Normal file
77
app/components/nuevas/MesesControl.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
"use client";
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
|
||||
// Multiselect de Mes de creación de la cohorte. Mismo patrón que OwnerControl: estado en la URL
|
||||
// (`meses=2026-05,2026-06`), sin el param = todos los meses marcados. No se puede dejar en 0.
|
||||
export default function MesesControl({ opciones, seleccion }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef(null);
|
||||
const [selected, setSelected] = useState(() => new Set(seleccion));
|
||||
const selRef = useRef(selected);
|
||||
const key = seleccion.join(",");
|
||||
|
||||
useEffect(() => {
|
||||
const next = new Set(seleccion);
|
||||
selRef.current = next;
|
||||
setSelected(next);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key]);
|
||||
|
||||
useEffect(() => {
|
||||
function onDocClick(e) {
|
||||
if (ref.current && !ref.current.contains(e.target)) setOpen(false);
|
||||
}
|
||||
document.addEventListener("mousedown", onDocClick);
|
||||
return () => document.removeEventListener("mousedown", onDocClick);
|
||||
}, []);
|
||||
|
||||
function applySet(nextSet) {
|
||||
selRef.current = nextSet;
|
||||
setSelected(nextSet);
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (nextSet.size === opciones.length) params.delete("meses");
|
||||
else params.set("meses", opciones.filter((o) => nextSet.has(o.k)).map((o) => o.k).join(","));
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
function toggle(k) {
|
||||
const next = new Set(selRef.current);
|
||||
if (next.has(k)) next.delete(k);
|
||||
else next.add(k);
|
||||
if (next.size === 0) return;
|
||||
applySet(next);
|
||||
}
|
||||
|
||||
const label =
|
||||
selected.size === opciones.length
|
||||
? "Todos los meses"
|
||||
: selected.size === 1
|
||||
? opciones.find((o) => selected.has(o.k))?.lbl
|
||||
: `${selected.size} meses`;
|
||||
|
||||
return (
|
||||
<div className="ctrl owner-ctrl" ref={ref}>
|
||||
<label>Mes de creación</label>
|
||||
<button type="button" className="owner-btn" onClick={() => setOpen((o) => !o)}>
|
||||
{label}
|
||||
</button>
|
||||
<div className={`owner-panel${open ? " open" : ""}`}>
|
||||
<div className="oa">
|
||||
<a onClick={() => applySet(new Set(opciones.map((o) => o.k)))}>Todos</a>
|
||||
</div>
|
||||
{opciones.map((o) => (
|
||||
<label className="owner-row" key={o.k}>
|
||||
<input type="checkbox" checked={selected.has(o.k)} onChange={() => toggle(o.k)} />
|
||||
{" "}
|
||||
{o.lbl}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
122
app/components/pipeline/AccionTable.js
Normal file
122
app/components/pipeline/AccionTable.js
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { DYN, money2 } from "../../lib/constants";
|
||||
import PrioridadBadge from "./PrioridadBadge";
|
||||
|
||||
// Tabla de "palancas" del Informe de Previsión — puerto de accionRowInforme()/accionTable()
|
||||
// (App Informe/assets/js/modals.js). Sin columna Ejecutivo/Bloqueo/Agendar a propósito: el informe
|
||||
// ya es de un solo dueño (va en el encabezado), y no es interactivo (es un snapshot para 1:1).
|
||||
const PLAN_LETRA = { "Plan A - En firma": "A", "Plan B - En Negociación": "B", "Plan C - En seguimiento": "C", "Plan D - Recalificar": "D" };
|
||||
const fechaTxt = (iso) => {
|
||||
if (!iso) return "—";
|
||||
const [y, m, d] = iso.split("-");
|
||||
return `${d}/${m}/${y.slice(2)}`;
|
||||
};
|
||||
|
||||
// `prevision`: columnas del informe imprimible de Previsión de Ventas (Cliente / Oportunidad, Plan,
|
||||
// Línea, MRR est., Prioridad, Nota de negociación, Fecha est. de cierre; sin Forecast ni Ejecutivo).
|
||||
export default function AccionTable({ list, prevision = false }) {
|
||||
if (!list.length) return <p className="hint">Ninguna oportunidad en esta categoría — bien ahí.</p>;
|
||||
const sorted = [...list].sort((a, b) => b.fc - a.fc);
|
||||
if (prevision) {
|
||||
return (
|
||||
<div className="tw">
|
||||
<div className="ts" style={{ maxHeight: "none" }}>
|
||||
<table className="accion-tbl accion-prev">
|
||||
<colgroup>
|
||||
<col style={{ width: "25%" }} />
|
||||
<col style={{ width: "6%" }} />
|
||||
<col style={{ width: "12%" }} />
|
||||
<col style={{ width: "9%" }} />
|
||||
<col style={{ width: "10%" }} />
|
||||
<col style={{ width: "25%" }} />
|
||||
<col style={{ width: "13%" }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente / Oportunidad</th>
|
||||
<th>Plan</th>
|
||||
<th>Línea</th>
|
||||
<th className="num">MRR est.</th>
|
||||
<th>Prioridad</th>
|
||||
<th>Nota de negociación</th>
|
||||
<th>Fecha Est. de cierre</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td className="dual-cel">
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a>
|
||||
<span className="sub">{o.cliente || "—"}</span>
|
||||
</td>
|
||||
<td>{PLAN_LETRA[o.plan] || "—"}</td>
|
||||
<td>{o.linea || "—"}</td>
|
||||
<td className="num">{money2(o.est)}</td>
|
||||
<td><PrioridadBadge o={o} /></td>
|
||||
<td style={{ color: "var(--tinta-suave)", fontSize: 11 }}>
|
||||
{(o.estado || "").slice(0, 110)}
|
||||
{(o.estado || "").length > 110 ? "…" : ""}
|
||||
</td>
|
||||
<td style={{ whiteSpace: "nowrap" }}>{fechaTxt(o.close)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="tot-fila">
|
||||
<td colSpan={3}>Total ({sorted.length} oport.)</td>
|
||||
<td className="num">{money2(sorted.reduce((a, o) => a + o.est, 0))}</td>
|
||||
<td colSpan={3} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="tw">
|
||||
<div className="ts" style={{ maxHeight: "none" }}>
|
||||
<table className="accion-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Prioridad</th>
|
||||
<th className="num">MRR est.</th>
|
||||
<th className="num">Forecast</th>
|
||||
<th>Nota de negociación</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td>
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||
{o.name}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<PrioridadBadge o={o} />
|
||||
</td>
|
||||
<td className="num">{money2(o.est)}</td>
|
||||
<td className="num">{money2(o.fc)}</td>
|
||||
<td style={{ color: "var(--tinta-suave)", fontSize: 12 }}>
|
||||
{(o.estado || "").slice(0, 90)}
|
||||
{(o.estado || "").length > 90 ? "…" : ""}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="tot-fila">
|
||||
<td colSpan={3}>Total ({sorted.length} oport.)</td>
|
||||
<td className="num">{money2(sorted.reduce((a, o) => a + o.est, 0))}</td>
|
||||
<td className="num">{money2(sorted.reduce((a, o) => a + o.fc, 0))}</td>
|
||||
<td />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
140
app/components/pipeline/AyudaPrevision.js
Normal file
140
app/components/pipeline/AyudaPrevision.js
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
// Glosario de la página de Previsión de Ventas: cómo se calcula o clasifica cada término que el
|
||||
// ejecutivo ve en las tarjetas y la tabla. Las reglas espejan app/lib/derive.js (movimiento,
|
||||
// actividad, pesos del plan) y el CLAUDE.md del proyecto (cortes del termómetro): si cambian
|
||||
// allá, actualizar acá.
|
||||
const TERMINOS = [
|
||||
{
|
||||
t: "¿Cuándo una oportunidad está «En movimiento» y cuándo «Estancada»?",
|
||||
c: (
|
||||
<>
|
||||
<p>Una oportunidad está <b>Estancada</b> si cumple <b>cualquiera</b> de estas dos condiciones:</p>
|
||||
<ul>
|
||||
<li>lleva <b>más de 14 días sin actividad registrada</b> en el CRM, o</li>
|
||||
<li>lleva <b>más de 30 días en la misma fase</b> del proceso.</li>
|
||||
</ul>
|
||||
<p>Si no cumple ninguna, está <b>En movimiento</b>. La tarjeta «Movimiento» cuenta cuántas hay de cada tipo; un clic sobre la cifra filtra la tabla.</p>
|
||||
<p className="ayuda-nota">Solo cuenta lo registrado en Dynamics. Si diste seguimiento por WhatsApp y no lo registraste como actividad, la oportunidad puede verse estancada aunque no lo esté.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Qué significan Plan A, Plan B y Plan C?",
|
||||
c: (
|
||||
<>
|
||||
<p>Es el campo <b>Plan de Cierre</b> de la oportunidad: indica qué tan cerca está de cerrarse.</p>
|
||||
<ul>
|
||||
<li><b>Plan A — En firma:</b> la más cercana al cierre. Peso en el forecast: <b>90%</b>.</li>
|
||||
<li><b>Plan B — En negociación:</b> se está negociando. Peso: <b>60%</b>.</li>
|
||||
<li><b>Plan C — En seguimiento:</b> se le da seguimiento, aún lejos del cierre. Peso: <b>30%</b>.</li>
|
||||
</ul>
|
||||
<p>Esta página solo incluye Plan A, B y C. Las oportunidades en <b>Plan D — Recalificar</b> o <b>Sin plan de cierre</b> no entran en la previsión.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Cómo se calcula el forecast ponderado?",
|
||||
c: (
|
||||
<>
|
||||
<p><b>Forecast = MRR estimado × peso del Plan de Cierre</b>, y se suma por oportunidad.</p>
|
||||
<p>Ejemplo: una oportunidad de $200 de MRR en Plan B aporta $200 × 60% = <b>$120</b> al forecast.</p>
|
||||
<p>Qué entra: oportunidades de tipo Venta - Cliente Nuevo, Up-Selling y Cross-Selling, en Plan A, B o C, con fecha estimada de cierre dentro de la ventana elegida.</p>
|
||||
<p className="ayuda-nota">El peso no considera la antigüedad: una oferta de hace 5 días pesa igual que una de hace 144. Por eso conviene leer el forecast junto con «Movimiento»: lo que está ponderado y a la vez estancado es lo que menos hay que dar por hecho. El porcentaje es una guía, no una predicción.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Cómo se clasifica en la temperatura?",
|
||||
c: (
|
||||
<>
|
||||
<p>La temperatura sale del <b>puntaje de la oportunidad</b>, que Dynamics calcula automáticamente. No es un porcentaje de probabilidad: el rango teórico va de 15 a 100 y en la práctica se observa entre 30 y 90.</p>
|
||||
<ul>
|
||||
<li><b>Fría:</b> 30 a 41</li>
|
||||
<li><b>Tibia:</b> 42 a 51</li>
|
||||
<li><b>Cálida:</b> 52 a 60</li>
|
||||
<li><b>Caliente:</b> 61 a 75</li>
|
||||
<li><b>Hirviendo:</b> 76 o más</li>
|
||||
</ul>
|
||||
<p>Los cortes se calibraron sobre la distribución real de las oportunidades, no en partes iguales. Se ve en la pestaña «Temperatura» de la matriz por ejecutivo.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Cómo se define la actividad (el punto de color en la tabla)?",
|
||||
c: (
|
||||
<>
|
||||
<p>Depende de los <b>días desde la última actividad registrada</b> en la oportunidad:</p>
|
||||
<ul>
|
||||
<li><b style={{ color: "#3f7d5c" }}>● Activa:</b> hasta 14 días</li>
|
||||
<li><b style={{ color: "#C98A1B" }}>● Tibia:</b> de 15 a 30 días</li>
|
||||
<li><b style={{ color: "#d1642a" }}>● Fría:</b> de 31 a 60 días</li>
|
||||
<li><b style={{ color: "#B23A2E" }}>● Congelada:</b> más de 60 días</li>
|
||||
</ul>
|
||||
<p className="ayuda-nota">Igual que en Movimiento, solo cuenta lo que quedó registrado en el CRM; el seguimiento por WhatsApp no aparece aquí.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Qué significan «Con agenda» y «Sin agenda»?",
|
||||
c: (
|
||||
<>
|
||||
<p><b>Con actividad agendada</b> = la oportunidad tiene una Tarea, Cita o Llamada pendiente con fecha entre hoy y el fin de la ventana seleccionada (el período de arriba: este mes, esta semana, etc.); la columna «Agenda» muestra la fecha de la más próxima. Las ya completadas o canceladas y las de días pasados no cuentan. <b>Sin agenda</b> = no tiene ninguna.</p>
|
||||
<p>La columna «Agendar» abre una Tarea, Cita o Llamada nueva ya ligada a la oportunidad; no se crea nada hasta que la guardas en Dynamics.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Qué es la ventana de tiempo y qué son las «Atrasadas»?",
|
||||
c: (
|
||||
<>
|
||||
<p>La ventana (Este mes, Esta semana, Próximo mes…) filtra por la <b>fecha estimada de cierre</b> de la oportunidad.</p>
|
||||
<p><b>Atrasadas</b> son las que no tienen fecha de cierre o la tienen en un mes que ya pasó. Hay que actualizarles la fecha o decidir qué hacer con ellas.</p>
|
||||
<p>En la tabla, el símbolo <b>⚠</b> junto al cierre marca una fecha estimada ya vencida.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Qué es la Prioridad?",
|
||||
c: (
|
||||
<>
|
||||
<p>Es el campo <b>Prioridad</b> de la oportunidad en Dynamics. Lo registra el ejecutivo; el informe solo lo muestra, no lo calcula.</p>
|
||||
<p>Es distinta del Plan de Cierre (A, B, C). El KPI «Alta Prioridad» cuenta las oportunidades marcadas como Alta y suma su MRR estimado.</p>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "¿Qué es la Luz Amarilla?",
|
||||
c: (
|
||||
<p>Es el <b>bloqueador que el ejecutivo declara</b> en la oportunidad (por ejemplo, Precio): lo que le impide avanzar. La tarjeta suma el forecast por cada bloqueador para ver qué frena más negocio.</p>
|
||||
),
|
||||
},
|
||||
{
|
||||
t: "Otros términos de la tabla",
|
||||
c: (
|
||||
<ul>
|
||||
<li><b>Segmento:</b> CA = Cartera Activa (clientes actuales: Up-Selling, Cross-Selling) · CN = Cliente Nuevo.</li>
|
||||
<li><b>Días:</b> cuántos días lleva la oportunidad en su fase actual.</li>
|
||||
<li><b>MRR est.:</b> ingreso mensual recurrente estimado de la oportunidad, sin ponderar.</li>
|
||||
<li><b>Forecast:</b> ese MRR ya multiplicado por el peso del Plan de Cierre.</li>
|
||||
</ul>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export default function AyudaPrevision() {
|
||||
return (
|
||||
<div style={{ marginTop: 28 }}>
|
||||
<div className="panel sec-oscura" style={{ marginBottom: 10 }}>
|
||||
<h3>Ayuda: cómo leer este informe</h3>
|
||||
<p className="hint" style={{ margin: 0 }}>Qué significa cada término y cómo se calcula. Haz clic en una pregunta para ver la respuesta.</p>
|
||||
</div>
|
||||
<div className="panel ayuda-prev">
|
||||
{TERMINOS.map((x) => (
|
||||
<details key={x.t}>
|
||||
<summary>{x.t}</summary>
|
||||
<div className="ayuda-cuerpo">{x.c}</div>
|
||||
</details>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
65
app/components/pipeline/ComparePanelMotivo.js
Normal file
65
app/components/pipeline/ComparePanelMotivo.js
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
import { money } from "../../lib/constants";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Barras Gana/Pierde apiladas por categoría + motivo de pérdida más frecuente — puerto de
|
||||
// comparePanelMotivo() (App Informe/assets/js/tables.js). `cats` viene de catsWonLost() (derive.js).
|
||||
// `dimKey` opcional: si se pasa, cada categoría es clicleable y filtra la página (ver Panel.js).
|
||||
export default function ComparePanelMotivo({ title, hint, cats, dimKey }) {
|
||||
const max = Math.max(...cats.flatMap((c) => [c.ganaV, c.pierdeV]), 0.1);
|
||||
const fmtV = (v) => (v < 20 ? `$${v.toFixed(2)}` : money(v));
|
||||
const Row = dimKey ? FilterableRow : "div";
|
||||
const rowProps = (k) => (dimKey ? { as: "div", pairs: [[dimKey, k]] } : {});
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{title}</h3>
|
||||
<p className="hint">{hint}</p>
|
||||
{cats.length === 0 ? (
|
||||
<p className="hint">Sin datos en este período.</p>
|
||||
) : (
|
||||
cats.map((c) => (
|
||||
<Row
|
||||
key={c.k}
|
||||
{...rowProps(c.k)}
|
||||
className={dimKey ? "cwm-row" : undefined}
|
||||
style={{ padding: "7px 4px", borderBottom: "1px solid var(--linea)" }}
|
||||
>
|
||||
<div style={{ fontSize: 12.5, marginBottom: 5, fontWeight: 700 }}>{c.k}</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
|
||||
<span style={{ fontSize: 10, color: "var(--gana)", width: 52 }}>Gana</span>
|
||||
<div className="bar-cell">
|
||||
<div className="bar-fill" style={{ width: `${((c.ganaV / max) * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
<span className="v">
|
||||
{fmtV(c.ganaV)}
|
||||
<span style={{ color: "var(--tinta-suave)" }}> ({c.ganaN})</span>
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<span style={{ fontSize: 10, color: "var(--pierde)", width: 52 }}>Pierde</span>
|
||||
<div className="bar-cell">
|
||||
<div className="bar-fill pierde" style={{ width: `${((c.pierdeV / max) * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
<span className="v">
|
||||
{fmtV(c.pierdeV)}
|
||||
<span style={{ color: "var(--tinta-suave)" }}> ({c.pierdeN})</span>
|
||||
</span>
|
||||
</div>
|
||||
{(c.topMotivo || c.depu > 0) && (
|
||||
<p className="hint" style={{ margin: "4px 0 0" }}>
|
||||
{c.topMotivo ? (
|
||||
<>
|
||||
Motivo principal de pérdida: <b>{c.topMotivo}</b> ({c.topMotivoN} de {c.pierdeN})
|
||||
{c.depu ? ` · ${c.depu} más son depuración sin motivo real` : ""}
|
||||
</>
|
||||
) : (
|
||||
<>{c.depu} de {c.pierdeN} pérdidas son depuración sin motivo real — no hay una razón de negocio clara aquí</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</Row>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
app/components/pipeline/DashBar.js
Normal file
28
app/components/pipeline/DashBar.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { money } from "../../lib/constants";
|
||||
import { agg } from "../../lib/derive";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Barra horizontal con doble medida (# y $) — equivalente de dashBar() (pages/resumen.js), con
|
||||
// cross-filter de clic vía FilterableRow (mismo patrón que Panel.js).
|
||||
export default function DashBar({ title, arr, dimKey }) {
|
||||
const rows = agg(arr, dimKey, (o) => o.val ?? o.actual ?? 0).sort((a, b) => b.v - a.v);
|
||||
const maxV = Math.max(...rows.map((d) => d.v), 1);
|
||||
return (
|
||||
<div className="panel dash-panel">
|
||||
<h3>{title}</h3>
|
||||
{rows.length ? (
|
||||
rows.map((d) => (
|
||||
<FilterableRow as="div" key={d.k} pairs={[[dimKey, d.k]]} className="dbar-row">
|
||||
<div className="dbar-top">
|
||||
<span className="nm">{d.k}</span>
|
||||
<span className="vals"><b>{d.n}</b><span className="c">{money(d.v)}</span></span>
|
||||
</div>
|
||||
<div className="bar-cell"><div className="bar-fill" style={{ width: `${((d.v / maxV) * 100).toFixed(1)}%` }} /></div>
|
||||
</FilterableRow>
|
||||
))
|
||||
) : (
|
||||
<p className="hint">Sin datos.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
46
app/components/pipeline/DashDonut.js
Normal file
46
app/components/pipeline/DashDonut.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { money } from "../../lib/constants";
|
||||
import { agg } from "../../lib/derive";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Donut para Segmento — equivalente de dashDonut() (pages/resumen.js), con cross-filter de clic
|
||||
// en la leyenda vía FilterableRow (mismo patrón que Panel.js/DashBar.js).
|
||||
export default function DashDonut({ title, arr, dimKey }) {
|
||||
const rows = agg(arr, dimKey, (o) => o.val ?? o.actual ?? 0).sort((a, b) => b.v - a.v);
|
||||
const total = rows.reduce((s, d) => s + d.v, 0) || 1;
|
||||
const R = 48, r = 30, C = 2 * Math.PI * R, cx = 64, cy = 64;
|
||||
let acc = 0;
|
||||
const color = (k) => (k === "Cartera Activa" ? "var(--alerta)" : "var(--marca)");
|
||||
const arcs = rows.map((d) => {
|
||||
const frac = d.v / total, len = frac * C, rot = (acc / C) * 360 - 90;
|
||||
acc += len;
|
||||
return (
|
||||
<circle
|
||||
key={d.k}
|
||||
cx={cx} cy={cy} r={R} fill="none" stroke={color(d.k)} strokeWidth={r}
|
||||
strokeDasharray={`${len.toFixed(2)} ${(C - len).toFixed(2)}`}
|
||||
transform={`rotate(${rot.toFixed(2)} ${cx} ${cy})`}
|
||||
// Tooltip vía atributo `title` (no `<title>` hijo): un `<title>` anidado dentro de <svg>
|
||||
// dispara un mismatch de hidratación real en este árbol (mismo fix que DonutChart.js).
|
||||
title={`${d.k}: ${d.n} oport. · ${money(d.v)}`}
|
||||
/>
|
||||
);
|
||||
});
|
||||
return (
|
||||
<div className="panel dash-panel">
|
||||
<h3>{title}</h3>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
|
||||
<svg viewBox="0 0 128 128" width="128" height="128">{arcs}</svg>
|
||||
<div style={{ flex: 1, minWidth: 150 }}>
|
||||
{rows.length ? rows.map((d) => (
|
||||
<FilterableRow as="div" key={d.k} pairs={[[dimKey, d.k]]} className="donut-leg-row">
|
||||
<span className="donut-dot" style={{ background: color(d.k) }} />
|
||||
<span className="nm">{d.k}</span>
|
||||
<span className="v">{d.n}</span>
|
||||
<span className="c">{money(d.v)}</span>
|
||||
</FilterableRow>
|
||||
)) : <p className="hint">Sin datos.</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
app/components/pipeline/DonutChart.js
Normal file
49
app/components/pipeline/DonutChart.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// Donut genérico (conteo, no monto) — mismo mecanismo que DashDonut.js (arcos SVG proporcionales
|
||||
// por longitud de circunferencia) pero con colores arbitrarios por categoría en vez de un binario
|
||||
// fijo. Usado para "Por Tipo de Actividad" (puerto de actDonutTipo(), App Informe/assets/js/pages/actividades.js).
|
||||
export default function DonutChart({ title, hint, rows, colorFor, valueLabel }) {
|
||||
const total = rows.reduce((s, d) => s + d.n, 0) || 1;
|
||||
const R = 48, r = 30, C = 2 * Math.PI * R, cx = 64, cy = 64;
|
||||
let acc = 0;
|
||||
const arcs = rows.map((d) => {
|
||||
const frac = d.n / total;
|
||||
const len = frac * C;
|
||||
const rot = (acc / C) * 360 - 90;
|
||||
acc += len;
|
||||
return (
|
||||
<circle
|
||||
key={d.k}
|
||||
cx={cx} cy={cy} r={R} fill="none" stroke={colorFor(d.k)} strokeWidth={r}
|
||||
strokeDasharray={`${len.toFixed(2)} ${(C - len).toFixed(2)}`}
|
||||
transform={`rotate(${rot.toFixed(2)} ${cx} ${cy})`}
|
||||
// Tooltip vía atributo `title` (no `<title>` hijo): un `<title>` anidado dentro de <svg>
|
||||
// dispara un mismatch de hidratación real en este árbol (confirmado en consola) — el
|
||||
// atributo evita esa clase de bug y el navegador igual muestra el tooltip nativo.
|
||||
title={`${d.k}: ${d.n} (${Math.round((d.n / total) * 100)}%)`}
|
||||
/>
|
||||
);
|
||||
});
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{title}</h3>
|
||||
{hint && <p className="hint">{hint}</p>}
|
||||
{rows.length ? (
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
|
||||
<svg viewBox="0 0 128 128" width="128" height="128">{arcs}</svg>
|
||||
<div style={{ flex: 1, minWidth: 150 }}>
|
||||
{rows.map((d) => (
|
||||
<div className="donut-leg-row" key={d.k}>
|
||||
<span className="donut-dot" style={{ background: colorFor(d.k) }} />
|
||||
<span className="nm">{d.k}</span>
|
||||
<span className="v">{d.n}</span>
|
||||
{valueLabel && <span className="c">{valueLabel(d)}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="hint">Sin datos.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
89
app/components/pipeline/ExecMatrix.js
Normal file
89
app/components/pipeline/ExecMatrix.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import React from "react";
|
||||
import { money } from "../../lib/constants";
|
||||
import { MTZ_DIMS, nomCorto } from "../../lib/derive";
|
||||
import SegTabs from "../SegTabs";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Matriz de ejecutivos × dimensión conmutable — puerto de mtzEjePanel() (assets/js/tables.js).
|
||||
// `dims`/`activeDim` dejan elegir la columna (Plan/Categoría Previsión/Actividad/Temperatura/Fase)
|
||||
// con pestañas — mismo patrón `SegTabs` + searchParam que el resto de la interactividad (Fase 1).
|
||||
export default function ExecMatrix({ arr, titulo, hint, valor, dims = MTZ_DIMS, activeDim }) {
|
||||
const val = valor || ((o) => o.est);
|
||||
const d = dims.find((x) => x.k === activeDim) || dims[0];
|
||||
const corto = d.corto;
|
||||
let cols = [...new Set(arr.map((o) => o[d.k]).filter(Boolean))];
|
||||
cols = d.orden ? cols.sort(d.orden) : cols;
|
||||
const ejes = [...new Set(arr.map((o) => o.owner))].sort(
|
||||
(a, b) => arr.filter((o) => o.owner === b).reduce((s, o) => s + val(o), 0) - arr.filter((o) => o.owner === a).reduce((s, o) => s + val(o), 0)
|
||||
);
|
||||
const cel = (ow, cv) => arr.filter((o) => o.owner === ow && o[d.k] === cv);
|
||||
const maxN = Math.max(...ejes.flatMap((ow) => cols.map((c) => cel(ow, c).length)), 1);
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{titulo || "Tubería por ejecutivo"}</h3>
|
||||
<p className="hint">{hint || "La intensidad del azul es la cantidad de oportunidades"}</p>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={dims.map((x) => ({ k: x.k, lbl: x.lbl }))} activeKey={d.k} paramName="mze" />
|
||||
</div>
|
||||
<div
|
||||
className="mze"
|
||||
style={{ gridTemplateColumns: `minmax(120px,1.4fr) repeat(${cols.length},minmax(58px,1fr)) minmax(74px,.9fr)` }}
|
||||
>
|
||||
<div className="mze-h eje" />
|
||||
{cols.map((c) => <div className="mze-h" key={c} title={c}>{corto(c)}</div>)}
|
||||
<div className="mze-h tot">Total</div>
|
||||
{ejes.map((ow) => {
|
||||
const tot = arr.filter((o) => o.owner === ow);
|
||||
return (
|
||||
<React.Fragment key={ow}>
|
||||
<FilterableRow as="div" pairs={[["owner", ow]]} className="mze-r">
|
||||
{nomCorto(ow)}
|
||||
</FilterableRow>
|
||||
{cols.map((c) => {
|
||||
const e = cel(ow, c);
|
||||
const alpha = e.length ? (0.1 + 0.55 * (e.length / maxN)).toFixed(2) : 0;
|
||||
return (
|
||||
<FilterableRow
|
||||
as="div"
|
||||
key={`${ow}-${c}`}
|
||||
pairs={[["owner", ow], [d.k, c]]}
|
||||
className={`mze-c${e.length ? "" : " vacia"}`}
|
||||
style={e.length ? { background: `rgba(30,113,184,${alpha})` } : undefined}
|
||||
>
|
||||
{e.length ? (
|
||||
<>
|
||||
<span className="n">{e.length}</span>
|
||||
<span className="v">{money(e.reduce((s, o) => s + val(o), 0))}</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="n vacio">·</span>
|
||||
)}
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
<div className="mze-c tot">
|
||||
<span className="n">{tot.length}</span>
|
||||
<span className="v">{money(tot.reduce((s, o) => s + val(o), 0))}</span>
|
||||
</div>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
<div className="mze-r tot">Total</div>
|
||||
{cols.map((c) => {
|
||||
const e = arr.filter((o) => o[d.k] === c);
|
||||
return (
|
||||
<div className="mze-c tot" key={`pie-${c}`}>
|
||||
<span className="n">{e.length}</span>
|
||||
<span className="v">{money(e.reduce((s, o) => s + val(o), 0))}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="mze-c tot">
|
||||
<span className="n">{arr.length}</span>
|
||||
<span className="v">{money(arr.reduce((s, o) => s + val(o), 0))}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
85
app/components/pipeline/MatrizCalidad.js
Normal file
85
app/components/pipeline/MatrizCalidad.js
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
import React from "react";
|
||||
import { money } from "../../lib/constants";
|
||||
import { CALIDAD_ORDER, CALIDAD_COLOR } from "../../lib/derive";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Matriz calidad × movimiento — el cruce que convierte "N estancadas" (inaccionable) en
|
||||
// "N oportunidades que el CRM califica como buenas y nadie mueve" (ver tables.js del sitio HTML).
|
||||
export default function MatrizCalidad({ arr, soloMovimiento = false, estatico = false }) {
|
||||
const cols = ["En movimiento", "Estancada"];
|
||||
|
||||
// Versión simple (Previsión de Ventas): solo cuántas están en movimiento y cuántas estancadas.
|
||||
if (soloMovimiento) {
|
||||
return (
|
||||
<div className="panel" id={estatico ? undefined : "mtzPanel"}>
|
||||
<h3>Movimiento</h3>
|
||||
<p className="hint">Oportunidades en movimiento contra estancadas{estatico ? "" : " (clic para filtrar)"}</p>
|
||||
<div className="mtz" style={{ gridTemplateColumns: "1fr 1fr" }}>
|
||||
{cols.map((c) => (
|
||||
<div className={`mtz-h${c === "Estancada" ? " alerta" : ""}`} key={c}>{c}</div>
|
||||
))}
|
||||
{cols.map((mv) => {
|
||||
const cls = `mtz-c${mv === "Estancada" ? " foco" : ""}`;
|
||||
const n = <span className="n" style={{ fontSize: 26 }}>{arr.filter((o) => o.mov === mv).length}</span>;
|
||||
return estatico ? (
|
||||
<div key={mv} className={cls} style={{ cursor: "default" }}>{n}</div>
|
||||
) : (
|
||||
<FilterableRow as="div" key={mv} pairs={[["mov", mv]]} className={cls}>{n}</FilterableRow>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const cel = (cal, mv) => arr.filter((o) => o.calidad === cal && o.mov === mv);
|
||||
const totCol = (mv) => arr.filter((o) => o.mov === mv);
|
||||
const filas = CALIDAD_ORDER.filter((cal) => arr.some((o) => o.calidad === cal));
|
||||
const foco = cel("Alta", "Estancada");
|
||||
|
||||
return (
|
||||
<div className="panel" id="mtzPanel">
|
||||
<h3>Calidad × movimiento</h3>
|
||||
<p className="hint">Termómetro (Alta = Caliente/Hirviendo) contra estancamiento</p>
|
||||
<div className="mtz">
|
||||
<div className="mtz-h" />
|
||||
{cols.map((c) => (
|
||||
<div className={`mtz-h${c === "Estancada" ? " alerta" : ""}`} key={c}>{c}</div>
|
||||
))}
|
||||
{filas.map((cal) => (
|
||||
<React.Fragment key={cal}>
|
||||
<div className="mtz-r">
|
||||
<span style={{ color: CALIDAD_COLOR[cal], fontWeight: 700 }}>●</span> {cal}
|
||||
</div>
|
||||
{cols.map((mv) => {
|
||||
const e = cel(cal, mv);
|
||||
const isFoco = cal === "Alta" && mv === "Estancada";
|
||||
return (
|
||||
<FilterableRow
|
||||
as="div"
|
||||
key={`${cal}-${mv}`}
|
||||
pairs={[["calidad", cal], ["mov", mv]]}
|
||||
className={`mtz-c${isFoco ? " foco" : ""}`}
|
||||
>
|
||||
<span className="n">{e.length}</span>
|
||||
<span className="v">{money(e.reduce((s, o) => s + o.est, 0))}</span>
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
</React.Fragment>
|
||||
))}
|
||||
<div className="mtz-r tot">Total</div>
|
||||
{cols.map((mv) => (
|
||||
<div className="mtz-c tot" key={`tot-${mv}`}>
|
||||
<span className="n">{totCol(mv).length}</span>
|
||||
<span className="v">{money(totCol(mv).reduce((s, o) => s + o.est, 0))}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="hint" style={{ marginTop: 10 }}>
|
||||
■ <b>{foco.length}</b> de calidad alta sin movimiento — <b>{money(foco.reduce((s, o) => s + o.est, 0))}</b>.
|
||||
Es la celda que hay que vaciar.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
app/components/pipeline/Panel.js
Normal file
58
app/components/pipeline/Panel.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import { money } from "../../lib/constants";
|
||||
import FilterableRow from "../FilterableRow";
|
||||
|
||||
// Panel de barras — puerto de `panel()` del sitio HTML (ver assets/js/tables.js). Si se pasa
|
||||
// `dimKey`, cada fila es clicleable y filtra la página entera por `o[dimKey] === d.k` (ver
|
||||
// lib/filterState.js); sin `dimKey` queda estático (paneles donde filtrar no aplica).
|
||||
export default function Panel({ title, hint, rows, cls, top, byVal, hideMoney, dimKey, keepOrder }) {
|
||||
let arr = rows;
|
||||
if (byVal && !keepOrder) arr = [...arr].sort((a, b) => b.v - a.v);
|
||||
const maxN = byVal ? Math.max(...arr.map((d) => d.v), 1) : Math.max(...arr.map((d) => d.n), 1);
|
||||
let vis = arr, resto = null;
|
||||
if (top && arr.length > top + 1) {
|
||||
vis = arr.slice(0, top);
|
||||
const r = arr.slice(top);
|
||||
resto = { n: r.reduce((a, d) => a + d.n, 0), v: r.reduce((a, d) => a + d.v, 0), k: r.length };
|
||||
}
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{title}</h3>
|
||||
{hint && <p className="hint">{hint}</p>}
|
||||
{vis.map((d) => {
|
||||
const inner = (
|
||||
<>
|
||||
<div className="bl">
|
||||
<span className="nm" title={d.k}>{d.k}</span>
|
||||
</div>
|
||||
<div className="bar-cell">
|
||||
<div className={`bar-fill ${cls || ""}`} style={{ width: `${(((byVal ? d.v : d.n) / maxN) * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
<span className="v">{d.n}</span>
|
||||
{!hideMoney && <span className="c">{money(d.v)}</span>}
|
||||
</>
|
||||
);
|
||||
return dimKey ? (
|
||||
<FilterableRow key={d.k} pairs={[[dimKey, d.k]]} className="row dual">
|
||||
{inner}
|
||||
</FilterableRow>
|
||||
) : (
|
||||
<div className="row dual static" key={d.k}>{inner}</div>
|
||||
);
|
||||
})}
|
||||
{resto && (
|
||||
<div className="row dual static">
|
||||
<div className="bl">
|
||||
<span className="nm" style={{ color: "var(--tinta-suave)", fontStyle: "italic" }}>
|
||||
Otros ({resto.k} categorías)
|
||||
</span>
|
||||
</div>
|
||||
<div className="bar-cell">
|
||||
<div className={`bar-fill ${cls || ""}`} style={{ width: `${(((byVal ? resto.v : resto.n) / maxN) * 100).toFixed(1)}%`, opacity: 0.45 }} />
|
||||
</div>
|
||||
<span className="v">{resto.n}</span>
|
||||
{!hideMoney && <span className="c">{money(resto.v)}</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
app/components/pipeline/PanelesCalidad.js
Normal file
18
app/components/pipeline/PanelesCalidad.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import Panel from "./Panel";
|
||||
import MatrizCalidad from "./MatrizCalidad";
|
||||
import { hayClasif, agg, aggOrd, CLASIF_ORDER } from "../../lib/derive";
|
||||
|
||||
// Termómetro + Luz Amarilla + Calidad×Movimiento — puerto de panelesCalidad() (modals.js). Se
|
||||
// reutiliza tal cual en los 4 informes individuales (Reporte Ejecutivo, Previsión, Renovación,
|
||||
// Previsión de Renovación) — mismos paneles que Tubería de Ventas, sin dimKey (el informe es un
|
||||
// snapshot para imprimir, no interactivo).
|
||||
export default function PanelesCalidad({ p }) {
|
||||
if (!p.length) return null;
|
||||
return (
|
||||
<div className="grid3" style={{ marginBottom: 22 }}>
|
||||
{hayClasif(p) && <Panel title="Termómetro" hint="Distribución de temperatura" rows={aggOrd(p, "clasif", CLASIF_ORDER, (o) => o.est)} />}
|
||||
<Panel title="Luz Amarilla — qué la detiene" hint="Bloqueador declarado por el ejecutivo" rows={agg(p, "luz", (o) => o.est)} cls="alerta" top={7} />
|
||||
{hayClasif(p) && <MatrizCalidad arr={p} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
app/components/pipeline/PanelesPrevision.js
Normal file
18
app/components/pipeline/PanelesPrevision.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import Panel from "./Panel";
|
||||
import MatrizCalidad from "./MatrizCalidad";
|
||||
import { agg, aggOrd, PLAN_ORDER } from "../../lib/derive";
|
||||
|
||||
// Tarjetas del Informe de Previsión (la hoja que se imprime): solo las cuatro más importantes, en una
|
||||
// fila compacta para que no ocupen más de ~1/4 de la hoja. Misma base que la página (forecast
|
||||
// ponderado), estáticas (sin clic para filtrar). Estilos en `.ind-grid.rep-ind` (components.css).
|
||||
export default function PanelesPrevision({ p }) {
|
||||
if (!p.length) return null;
|
||||
return (
|
||||
<div className="ind-grid rep-ind" style={{ marginBottom: 16 }}>
|
||||
<Panel title="Forecast por Plan de Cierre" rows={aggOrd(p, "plan", PLAN_ORDER, (o) => o.fc)} byVal keepOrder />
|
||||
<Panel title="Por Tipo de Oportunidad" rows={agg(p, "tipo", (o) => o.fc)} byVal />
|
||||
<MatrizCalidad arr={p} soloMovimiento estatico />
|
||||
<Panel title="Luz Amarilla" rows={agg(p, "luz", (o) => o.fc)} cls="alerta" top={4} byVal />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
12
app/components/pipeline/PrioridadBadge.js
Normal file
12
app/components/pipeline/PrioridadBadge.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { PRIORIDAD_COLOR } from "../../lib/derive";
|
||||
|
||||
// Etiqueta de color de la prioridad que el ejecutivo registró en la oportunidad (campo de Dynamics).
|
||||
export default function PrioridadBadge({ o }) {
|
||||
const n = o.prioridad || "Sin prioridad";
|
||||
const c = PRIORIDAD_COLOR[n] || PRIORIDAD_COLOR["Sin prioridad"];
|
||||
return (
|
||||
<span title="Prioridad registrada en la oportunidad (Dynamics)" style={{ background: c.bg, color: c.fg, fontWeight: 700, fontSize: 11, padding: "2px 8px", borderRadius: 8, whiteSpace: "nowrap" }}>
|
||||
{n === "Sin prioridad" ? "—" : n}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
49
app/components/pipeline/RepTable.js
Normal file
49
app/components/pipeline/RepTable.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { DYN, ACT_COLOR, money2 } from "../../lib/constants";
|
||||
import { cierreVencido } from "../../lib/derive";
|
||||
|
||||
// Tabla del informe individual — puerto de repRow()/repTable() (App Informe/assets/js/modals.js).
|
||||
export default function RepTable({ arr }) {
|
||||
if (!arr.length) return <p className="hint">Ninguna oportunidad en esta categoría — bien ahí.</p>;
|
||||
const sorted = [...arr].sort((a, b) => b.est - a.est);
|
||||
return (
|
||||
<div className="tw">
|
||||
<div className="ts" style={{ maxHeight: "none" }}>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Plan cierre</th>
|
||||
<th>Fase actual</th>
|
||||
<th>Actividad</th>
|
||||
<th className="num">MRR est.</th>
|
||||
<th>Cierre est.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td>
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||
{o.name}
|
||||
</a>
|
||||
</td>
|
||||
<td>{(o.plan || "").replace(" - ", " ")}</td>
|
||||
<td>{o.faseActual || "—"}</td>
|
||||
<td>
|
||||
<span style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }}>● {o.actividad}</span>
|
||||
</td>
|
||||
<td className="num">{money2(o.est)}</td>
|
||||
<td>
|
||||
{o.close || "—"}
|
||||
{cierreVencido(o) ? " ⚠" : ""}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
166
app/components/pipeline/TablaPipe.js
Normal file
166
app/components/pipeline/TablaPipe.js
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import PrioridadBadge from "./PrioridadBadge";
|
||||
import { DYN, ACT_COLOR, money, money2, nuevaActividadUrl, TIPOS_NUEVA_ACTIVIDAD } from "../../lib/constants";
|
||||
|
||||
const PLAN_LETRA = {
|
||||
"Plan A - En firma": "A", "Plan B - En Negociación": "B", "Plan C - En seguimiento": "C",
|
||||
"Plan D - Recalificar": "D", "Sin plan de cierre": "—",
|
||||
};
|
||||
const nomCorto = (n) => {
|
||||
const p = (n || "").split(" ");
|
||||
return p.length > 2 ? `${p[0]} ${p[p.length - 2]}` : n || "";
|
||||
};
|
||||
function cierreVencido(o) {
|
||||
return !!o.close && o.close < new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
// Tabla de tubería para el layout split23 (2/3 der.): columna Cliente/Oportunidad fija, scroll
|
||||
// horizontal — mismo tratamiento que `tablePipe(arr,tipo,split=true,...)` del sitio HTML
|
||||
// (assets/js/tables.js). Sin agrupado por actividad agendada todavía (necesita datos de
|
||||
// Actividades, que esta app aún no consulta) y sin clic-para-agendar.
|
||||
export default function TablaPipe({ arr, tipo, agendar = false, total = false }) {
|
||||
const colFc = tipo === "fc";
|
||||
const sorted = [...arr].sort((a, b) => b.est - a.est);
|
||||
return (
|
||||
<div className="tw split">
|
||||
<div className="ts">
|
||||
<table className={`fix${agendar ? " fit-all" : ""}`}>
|
||||
<colgroup>
|
||||
{agendar ? (
|
||||
<>
|
||||
<col style={{ width: "17%" }} />
|
||||
<col style={{ width: "44px" }} />
|
||||
<col style={{ width: "36px" }} />
|
||||
<col style={{ width: "6%" }} />
|
||||
<col style={{ width: "6%" }} />
|
||||
<col style={{ width: "6%" }} />
|
||||
<col style={{ width: "40px" }} />
|
||||
<col style={{ width: "56px" }} />
|
||||
<col style={{ width: "58px" }} />
|
||||
<col style={{ width: "6%" }} />
|
||||
<col style={{ width: "62px" }} />
|
||||
{colFc && <col style={{ width: "66px" }} />}
|
||||
<col style={{ width: "62px" }} />
|
||||
<col style={{ width: "80px" }} />
|
||||
<col style={{ width: "132px" }} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<col style={{ width: "20%" }} />
|
||||
<col style={{ width: "64px" }} />
|
||||
<col style={{ width: "32px" }} />
|
||||
<col style={{ width: "8.5%" }} />
|
||||
<col style={{ width: "8.5%" }} />
|
||||
<col style={{ width: "8.5%" }} />
|
||||
<col style={{ width: "36px" }} />
|
||||
<col style={{ width: "70px" }} />
|
||||
<col style={{ width: "9%" }} />
|
||||
<col style={{ width: "8.5%" }} />
|
||||
{colFc && <col style={{ width: "7.5%" }} />}
|
||||
<col style={{ width: "7%" }} />
|
||||
</>
|
||||
)}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente / Oportunidad</th>
|
||||
<th>Segmento</th>
|
||||
<th title="Plan de cierre">Plan</th>
|
||||
<th>Línea</th>
|
||||
<th>Competidor</th>
|
||||
<th>Fase</th>
|
||||
<th className="num" title="Días en la fase actual">Días</th>
|
||||
<th>Actividad</th>
|
||||
{agendar && <th>Prioridad</th>}
|
||||
<th>Ejecutivo</th>
|
||||
<th className="num">MRR est.</th>
|
||||
{colFc && <th className="num">Forecast</th>}
|
||||
<th>Cierre</th>
|
||||
{agendar && <th title="Si ya tiene una Tarea/Cita/Llamada agendada en la ventana">Agenda</th>}
|
||||
{agendar && <th>Agendar</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id} style={agendar && !o.actFecha ? { boxShadow: "inset 3px 0 0 var(--pierde, #B23A2E)" } : undefined}>
|
||||
<td className="dual-cel">
|
||||
{o.actFecha && (
|
||||
<span title={`Actividad agendada para el ${o.actFecha}`}>📅 </span>
|
||||
)}
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener" title={o.name}>
|
||||
{o.name}
|
||||
</a>
|
||||
<span className="sub" title={o.cliente || ""}>{o.cliente || "—"}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`} title={o.segmento}>
|
||||
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`plan-b p${PLAN_LETRA[o.plan] || "x"}`} title={o.plan || "Sin plan de cierre"}>
|
||||
{PLAN_LETRA[o.plan] || "—"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="elip" title={o.linea || ""}>{o.linea || "—"}</td>
|
||||
<td className="elip" title={o.competidor || ""}>
|
||||
{o.competidor === "Sin registrar" ? "—" : o.competidor || "—"}
|
||||
</td>
|
||||
<td className="elip" title={o.faseActual || ""}>{o.faseActual || "—"}</td>
|
||||
<td className="num">{o.diasEnFase == null ? "—" : o.diasEnFase}</td>
|
||||
<td style={{ textAlign: "center" }}>
|
||||
<span
|
||||
style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }}
|
||||
title={`${o.actividad}${o.estanc ? " · estancada" : ""}`}
|
||||
>
|
||||
●
|
||||
</span>
|
||||
</td>
|
||||
{agendar && <td><PrioridadBadge o={o} /></td>}
|
||||
<td className="elip" title={o.owner}>{nomCorto(o.owner)}</td>
|
||||
<td className="num">{money(o.est)}</td>
|
||||
{colFc && <td className="num">{money(o.fc)}</td>}
|
||||
<td className={`num${cierreVencido(o) ? " venc" : ""}`} title={cierreVencido(o) ? "Fecha de cierre vencida al corte" : ""}>
|
||||
{o.close ? o.close.slice(5) : "—"}
|
||||
{cierreVencido(o) ? " ⚠" : ""}
|
||||
</td>
|
||||
{agendar && (
|
||||
<td>
|
||||
{o.actFecha ? (
|
||||
<span style={{ color: "#3f7d5c", fontWeight: 700 }} title={`Actividad agendada para el ${o.actFecha}`}>
|
||||
📅 {o.actFecha.split("-").reverse().slice(0, 2).join("/")}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ color: "#B23A2E", fontWeight: 700 }} title="Sin Tarea/Cita/Llamada agendada en la ventana">Sin agenda</span>
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
{agendar && (
|
||||
<td>
|
||||
<span className="plan-agenda-btns">
|
||||
{TIPOS_NUEVA_ACTIVIDAD.map((t) => (
|
||||
<a key={t.etn} className="plan-agendar" href={nuevaActividadUrl({ id: o.id, nombre: o.name }, t.etn)} target="_blank" rel="noopener" title={t.ayuda}>
|
||||
+ {t.label}
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
{total && (
|
||||
<tfoot>
|
||||
<tr className="tot-fila">
|
||||
<td>Total ({sorted.length} oport.)</td>
|
||||
<td colSpan={agendar ? 9 : 8} />
|
||||
<td className="num">{money(sorted.reduce((a, o) => a + o.est, 0))}</td>
|
||||
{colFc && <td className="num">{money(sorted.reduce((a, o) => a + o.fc, 0))}</td>}
|
||||
<td colSpan={agendar ? 3 : 1} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
)}
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
91
app/components/pipeline/TablaPrevision.js
Normal file
91
app/components/pipeline/TablaPrevision.js
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import PrioridadBadge from "./PrioridadBadge";
|
||||
import { DYN, ACT_COLOR, money, nuevaActividadUrl, TIPOS_NUEVA_ACTIVIDAD } from "../../lib/constants";
|
||||
import { nomCorto } from "../../lib/derive";
|
||||
|
||||
const PLAN_LETRA = {
|
||||
"Plan A - En firma": "A", "Plan B - En Negociación": "B", "Plan C - En seguimiento": "C",
|
||||
"Plan D - Recalificar": "D", "Sin plan de cierre": "—",
|
||||
};
|
||||
const cierreVencido = (o) => !!o.close && o.close < new Date().toISOString().slice(0, 10);
|
||||
|
||||
// Tabla única de Previsión de Ventas: la usan la lista principal («Oportunidades con cierre estimado en
|
||||
// esta ventana») y las tres de «Oportunidades para accionar». Mismas columnas, mismo orden y mismos
|
||||
// anchos, para que se alineen de arriba hacia abajo. Sin scroll horizontal en escritorio (anchos
|
||||
// en `.fit-all`, components.css).
|
||||
const COLS = [
|
||||
"14%", "34px", "7%", "8%", "58px", "66px", "16%", "66px", "82px", "190px", "54px",
|
||||
];
|
||||
|
||||
export default function TablaPrevision({ arr }) {
|
||||
const sorted = [...arr].sort((a, b) => b.est - a.est);
|
||||
return (
|
||||
<div className="tw split">
|
||||
<div className="ts">
|
||||
<table className="fix fit-all">
|
||||
<colgroup>{COLS.map((w, i) => <col key={i} style={{ width: w }} />)}</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente / Oportunidad</th>
|
||||
<th title="Plan de cierre">Plan</th>
|
||||
<th>Línea</th>
|
||||
<th>Ejecutivo</th>
|
||||
<th className="num">MRR est.</th>
|
||||
<th>Prioridad</th>
|
||||
<th>Nota de negociación</th>
|
||||
<th>Fecha Est. de cierre</th>
|
||||
<th title="Si ya tiene una Tarea/Cita/Llamada agendada en la ventana">Agenda</th>
|
||||
<th>Agendar</th>
|
||||
<th title="Días desde la última actividad registrada">Actividad</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id} style={!o.actFecha ? { boxShadow: "inset 3px 0 0 var(--pierde, #B23A2E)" } : undefined}>
|
||||
<td className="dual-cel">
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener" title={o.name}>{o.name}</a>
|
||||
<span className="sub" title={o.cliente || ""}>{o.cliente || "—"}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`plan-b p${PLAN_LETRA[o.plan] || "x"}`} title={o.plan || "Sin plan de cierre"}>{PLAN_LETRA[o.plan] || "—"}</span>
|
||||
</td>
|
||||
<td className="elip" title={o.linea || ""}>{o.linea || "—"}</td>
|
||||
<td className="elip" title={o.owner}>{nomCorto(o.owner)}</td>
|
||||
<td className="num">{money(o.est)}</td>
|
||||
<td><PrioridadBadge o={o} /></td>
|
||||
<td className="nota-cel" title={o.estado || ""}>{o.estado ? (o.estado.length > 110 ? `${o.estado.slice(0, 110)}…` : o.estado) : "—"}</td>
|
||||
<td className={`num${cierreVencido(o) ? " venc" : ""}`} title={cierreVencido(o) ? "Fecha de cierre vencida al corte" : ""}>
|
||||
{o.close ? `${o.close.slice(8, 10)}/${o.close.slice(5, 7)}/${o.close.slice(2, 4)}` : "—"}{cierreVencido(o) ? " ⚠" : ""}
|
||||
</td>
|
||||
<td>
|
||||
{o.actFecha ? (
|
||||
<span style={{ color: "#3f7d5c", fontWeight: 700 }} title={`Actividad agendada para el ${o.actFecha}`}>📅 {o.actFecha.split("-").reverse().slice(0, 2).join("/")}</span>
|
||||
) : (
|
||||
<span style={{ color: "#B23A2E", fontWeight: 700 }} title="Sin Tarea/Cita/Llamada agendada en la ventana">Sin agenda</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<span className="plan-agenda-btns">
|
||||
{TIPOS_NUEVA_ACTIVIDAD.map((t) => (
|
||||
<a key={t.etn} className="plan-agendar" href={nuevaActividadUrl({ id: o.id, nombre: o.name }, t.etn)} target="_blank" rel="noopener" title={t.ayuda}>+ {t.label}</a>
|
||||
))}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ textAlign: "center" }}>
|
||||
<span style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }} title={`${o.actividad}${o.estanc ? " · estancada" : ""}`}>●</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="tot-fila">
|
||||
<td>Total ({sorted.length} oport.)</td>
|
||||
<td colSpan={3} />
|
||||
<td className="num">{money(sorted.reduce((a, o) => a + o.est, 0))}</td>
|
||||
<td colSpan={6} />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
50
app/components/pipeline/VelPanel.js
Normal file
50
app/components/pipeline/VelPanel.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// Velocidad de movimiento — puerto de velPanel() (App Informe/assets/js/tables.js). `vel` viene de
|
||||
// pipeVelFor() (derive.js), ya ordenado de más lenta a más rápida y sin fases vacías.
|
||||
export default function VelPanel({ title, hint, vel }) {
|
||||
if (!vel.length) {
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{title}</h3>
|
||||
<p className="hint">Sin duraciones de fase registradas para este conjunto.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const max = Math.max(...vel.map((v) => v.prom), 0.1);
|
||||
const slow = vel[0];
|
||||
const divergeSlow = slow.mediana != null && slow.mediana > 0 && Math.abs(slow.prom - slow.mediana) / slow.mediana > 0.25;
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>{title}</h3>
|
||||
<p className="hint">{hint} · La barra es días promedio en cada fase antes de avanzar.</p>
|
||||
{vel.map((v) => {
|
||||
const diverge = v.mediana != null && v.mediana > 0 && Math.abs(v.prom - v.mediana) / v.mediana > 0.25;
|
||||
return (
|
||||
<div className="row static" key={v.fase}>
|
||||
<div className="bl">
|
||||
<span className="nm">{v.fase}</span>
|
||||
</div>
|
||||
<div className="bar-cell">
|
||||
<div className="bar-fill alerta" style={{ width: `${((v.prom / max) * 100).toFixed(1)}%` }} />
|
||||
</div>
|
||||
<span className="v">
|
||||
{v.prom.toFixed(2)} d
|
||||
{diverge && (
|
||||
<span style={{ color: "var(--tinta-suave)", fontWeight: 400 }}> (mediana {v.mediana.toFixed(1)}d)</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<p className="hint" style={{ marginTop: 10 }}>
|
||||
Fase más lenta: <b>{slow.fase}</b> ({slow.prom.toFixed(1)} días promedio).
|
||||
{divergeSlow && (
|
||||
<>
|
||||
{" "}La mediana ahí es <b>{slow.mediana.toFixed(1)}d</b> — el promedio lo empuja hacia arriba un puñado de
|
||||
casos como <b>{slow.peor.name}</b> ({slow.peor.dur.toFixed(0)} días), no que la fase entera sea así de lenta.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
55
app/components/pipeline/WonTable.js
Normal file
55
app/components/pipeline/WonTable.js
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import { DYN, money2 } from "../../lib/constants";
|
||||
|
||||
// Tabla de detalle de ganadas — equivalente de tableWon() (assets/js/tables.js), sin el orden
|
||||
// clicleable por encabezado (limitación conocida de esta v1).
|
||||
export default function WonTable({ rows, title, locked }) {
|
||||
const sorted = [...rows].sort((a, b) => (b.val ?? b.actual ?? 0) - (a.val ?? a.actual ?? 0));
|
||||
return (
|
||||
<div className="tw">
|
||||
{title && (
|
||||
<div className="tw-title">
|
||||
<h3>{title}</h3>
|
||||
<span className="tw-count">{sorted.length} oportunidades</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Seg.</th>
|
||||
{!locked && <th>Ejecutivo</th>}
|
||||
<th>Tipo</th>
|
||||
<th>Línea de Negocio</th>
|
||||
<th>Origen</th>
|
||||
<th className="num">MRR</th>
|
||||
<th>Cierre</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td className="wrap-p">{o.cliente || "—"}</td>
|
||||
<td className="wrap-p">
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||
</span>
|
||||
</td>
|
||||
{!locked && <td>{o.owner}</td>}
|
||||
<td>{o.tipo}</td>
|
||||
<td>{o.linea}</td>
|
||||
<td className="wrap-p">{o.origen}</td>
|
||||
<td className="num">{money2(o.val ?? o.actual)}</td>
|
||||
<td>{o.actualClose || o.cierre || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
228
app/components/plan/AgendadorPanel.js
Normal file
228
app/components/plan/AgendadorPanel.js
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { money, actividadUrl } from "../../lib/constants";
|
||||
import { diaCorto } from "../../lib/plan";
|
||||
import {
|
||||
AGENDADOR, TIPOS_AGENDADOR, OBJETIVOS_AGENDADOR, proponer, validar, horasDe, minAHora, horaAMin,
|
||||
} from "../../lib/agendador";
|
||||
import { crearLoteAction, deshacerLoteAction } from "../../actividades/agendadorActions";
|
||||
|
||||
const NOMBRE_PLURAL = { Llamada: "llamadas", Cita: "visitas", Tarea: "tareas" };
|
||||
const fechaHora = (iso) =>
|
||||
new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(iso));
|
||||
|
||||
// Agendador sugerido de la semana (PILOTO). Propone una actividad por oportunidad «por planificar»,
|
||||
// con el objetivo sugerido, repartidas en la semana dentro del horario y los máximos por día; la
|
||||
// persona revisa y cambia lo que quiera, y «Crear en Dynamics» las crea de una vez, con el propietario
|
||||
// de la oportunidad. Nada se escribe hasta ese botón. Diseño: agendador-automatico-diseno.md.
|
||||
export default function AgendadorPanel({ ownerEmail, ownerName, periodo, dias, hoy, ahoraMin, candidatos, existentes, bloques, lotes }) {
|
||||
const router = useRouter();
|
||||
const [pendiente, empezar] = useTransition();
|
||||
const base = { dias, existentes, bloques, hoy, ahoraMin };
|
||||
const [tipoTodas, setTipoTodas] = useState("Llamada");
|
||||
const [items, setItems] = useState(() => proponer({ candidatos, ...base, tipo: "Llamada" }));
|
||||
const [resultado, setResultado] = useState(null);
|
||||
const [aviso, setAviso] = useState(null);
|
||||
|
||||
const incluidos = items.filter((i) => i.incluir && !i.creada);
|
||||
const val = useMemo(() => validar({ items: incluidos, ...base }), [items, dias, existentes, bloques, hoy, ahoraMin]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const cambiar = (key, cambios) => setItems((prev) => prev.map((i) => (i.key === key ? { ...i, ...cambios } : i)));
|
||||
|
||||
const cambiarTipo = (it, tipo) => {
|
||||
const horas = horasDe(tipo).map(minAHora);
|
||||
const hora = tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : horas.includes(it.hora) ? it.hora : horas[0];
|
||||
cambiar(it.key, { tipo, hora });
|
||||
};
|
||||
const cambiarDia = (it, dia) => {
|
||||
const horas = horasDe(it.tipo).map(minAHora);
|
||||
const hora = it.tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : it.hora && horas.includes(it.hora) ? it.hora : horas[0] || "";
|
||||
cambiar(it.key, { dia: dia || null, hora: dia ? hora : null, incluir: !!dia || it.incluir, sinCupo: !dia });
|
||||
};
|
||||
const reproponer = (tipo) => {
|
||||
setTipoTodas(tipo);
|
||||
const nuevos = proponer({ candidatos: candidatos.filter((c) => !items.find((i) => i.key === c.id)?.creada), ...base, tipo });
|
||||
setItems([...items.filter((i) => i.creada), ...nuevos]);
|
||||
};
|
||||
|
||||
const crear = () => {
|
||||
setAviso(null);
|
||||
if (!incluidos.length || !val.ok) return;
|
||||
const resumen = TIPOS_AGENDADOR.map((t) => [t, incluidos.filter((i) => i.tipo === t).length]).filter(([, n]) => n).map(([t, n]) => `${n} ${NOMBRE_PLURAL[t]}`).join(", ");
|
||||
if (!window.confirm(`Se crearán en Dynamics ${incluidos.length} actividades (${resumen}) para ${ownerName}, a su nombre. ¿Continuar?`)) return;
|
||||
empezar(async () => {
|
||||
const r = await crearLoteAction({
|
||||
ownerEmail,
|
||||
periodo,
|
||||
items: incluidos.map((i) => ({ oppId: i.oppId, nombre: i.nombre, cliente: i.cliente, tipo: i.tipo, objetivo: i.objetivo, dia: i.dia, hora: i.hora })),
|
||||
});
|
||||
if (!r.ok) { setAviso({ mal: true, texto: r.error }); return; }
|
||||
const creadas = new Map(r.resultados.filter((x) => x.estado === "creada").map((x) => [x.oppId, x]));
|
||||
setItems((prev) => prev.map((i) => (creadas.has(i.oppId) ? { ...i, creada: creadas.get(i.oppId) } : i)));
|
||||
setResultado(r);
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const deshacer = (id) => {
|
||||
if (!window.confirm("Se cancelarán en Dynamics las actividades de esa tanda que sigan abiertas. ¿Deshacer?")) return;
|
||||
empezar(async () => {
|
||||
const r = await deshacerLoteAction(id);
|
||||
setAviso(r.ok ? { texto: `Tanda deshecha: ${r.canceladas} cancelada(s)${r.yaCerradas ? `, ${r.yaCerradas} ya estaban cerradas` : ""}${r.errores ? `, ${r.errores} con error` : ""}.` } : { mal: true, texto: r.error });
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const hayCitas = incluidos.some((i) => i.tipo === "Cita");
|
||||
|
||||
return (
|
||||
<section className="panel plan-agd no-print">
|
||||
<h3>Agendador de la semana — {ownerName} <span className="agd-piloto">piloto</span></h3>
|
||||
<p className="hint">
|
||||
Propone una actividad por cada oportunidad por planificar, con el objetivo sugerido, repartidas de lunes a viernes entre 9:00–12:00 y
|
||||
14:00–16:00 (máximo por día: {AGENDADOR.topes.Llamada} llamadas, {AGENDADOR.topes.Cita} visitas, {AGENDADOR.topes.Tarea} tareas). Revisa y cambia lo que
|
||||
quieras; no se crea nada en Dynamics hasta que pulses «Crear». Quedan a nombre del propietario de la oportunidad.
|
||||
</p>
|
||||
|
||||
{candidatos.length === 0 ? (
|
||||
<p>No hay oportunidades por planificar esta semana: todas tienen alguna actividad.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="agd-barra">
|
||||
<label htmlFor="agd-tipo">Tipo para todas:</label>
|
||||
<select id="agd-tipo" value={tipoTodas} onChange={(e) => reproponer(e.target.value)} disabled={pendiente}>
|
||||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||||
</select>
|
||||
<button type="button" className="agd-btn-sec" onClick={() => reproponer(tipoTodas)} disabled={pendiente} title="Vuelve a repartir todas las que no se han creado">Proponer de nuevo</button>
|
||||
<span className="hint">
|
||||
{incluidos.length} propuesta{incluidos.length === 1 ? "" : "s"} para crear
|
||||
{items.filter((i) => i.sinCupo && !i.dia && !i.creada).length > 0 && ` · ${items.filter((i) => i.sinCupo && !i.dia && !i.creada).length} sin cupo esta semana (no caben con los máximos por día)`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="agd-dias">
|
||||
{dias.map((d) => {
|
||||
const c = val.porDia[d] || { Llamada: 0, Cita: 0, Tarea: 0, ...(existentes[d] || {}) };
|
||||
const exc = TIPOS_AGENDADOR.some((t) => c[t] > AGENDADOR.topes[t]);
|
||||
return (
|
||||
<span key={d} className={`agd-dia${exc ? " mal" : ""}`} title="Incluye lo que ya tiene agendado ese día">
|
||||
<b>{diaCorto(d)}</b> {c.Llamada} llam. · {c.Cita} vis. · {c.Tarea} tar.
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="ts" style={{ maxHeight: 520, overflowY: "auto" }}>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Cliente / oportunidad</th>
|
||||
<th className="num">Valor</th>
|
||||
<th>Tipo</th>
|
||||
<th>Día</th>
|
||||
<th>Hora</th>
|
||||
<th>Objetivo</th>
|
||||
<th>Avisos</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((it) => {
|
||||
const probs = val.porItem[it.key] || [];
|
||||
const horas = horasDe(it.tipo).map(minAHora);
|
||||
return (
|
||||
<tr key={it.key} style={it.creada ? { opacity: 0.6 } : undefined}>
|
||||
<td>
|
||||
<input type="checkbox" checked={!!it.incluir && !it.creada} disabled={!!it.creada || pendiente} onChange={(e) => cambiar(it.key, { incluir: e.target.checked })} aria-label="Incluir" />
|
||||
</td>
|
||||
<td>
|
||||
<strong>{it.cliente || it.nombre}</strong>
|
||||
{it.cliente && <div style={{ fontSize: 11, color: "var(--tinta-suave)" }}>{it.nombre}</div>}
|
||||
</td>
|
||||
<td className="num">{money(it.valor)}{it.pct ? <div style={{ fontSize: 11, color: "var(--tinta-suave)" }}>{it.pct}%</div> : null}</td>
|
||||
<td>
|
||||
<select value={it.tipo} disabled={!!it.creada || pendiente} onChange={(e) => cambiarTipo(it, e.target.value)}>
|
||||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<select value={it.dia || ""} disabled={!!it.creada || pendiente} onChange={(e) => cambiarDia(it, e.target.value)}>
|
||||
<option value="">— elegir —</option>
|
||||
{dias.map((d) => <option key={d} value={d}>{diaCorto(d)}</option>)}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
{it.tipo === "Tarea" ? (
|
||||
<span title="Las tareas vencen a las 16:00">vence {minAHora(AGENDADOR.horaTarea)}</span>
|
||||
) : (
|
||||
<select value={it.hora || ""} disabled={!!it.creada || pendiente || !it.dia} onChange={(e) => cambiar(it.key, { hora: e.target.value })}>
|
||||
<option value="">—</option>
|
||||
{horas.map((h) => <option key={h} value={h}>{h}</option>)}
|
||||
</select>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<select value={it.objetivo} disabled={!!it.creada || pendiente} onChange={(e) => cambiar(it.key, { objetivo: e.target.value })}>
|
||||
<option value="">— elegir —</option>
|
||||
{OBJETIVOS_AGENDADOR.map((o) => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
{it.creada ? (
|
||||
<a className="agd-ok" href={actividadUrl({ tipo: it.creada.tipo, id: it.creada.activityId })} target="_blank" rel="noreferrer">✓ Creada · abrir en CRM</a>
|
||||
) : it.sinCupo && !it.dia ? (
|
||||
<span className="agd-mal">Sin cupo esta semana: elige un día o déjala fuera.</span>
|
||||
) : it.incluir && probs.length ? (
|
||||
<span className="agd-mal">{probs.join(" ")}</span>
|
||||
) : it.tipo === "Cita" && it.incluir ? (
|
||||
<span className="hint">Se crea genérica: completa lugar y participantes en el CRM.</span>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="agd-pie">
|
||||
<button type="button" className="agd-btn" disabled={pendiente || !incluidos.length || !val.ok} onClick={crear}>
|
||||
{pendiente ? "Trabajando…" : `Crear ${incluidos.length} actividad${incluidos.length === 1 ? "" : "es"} en Dynamics`}
|
||||
</button>
|
||||
{!val.ok && incluidos.length > 0 && <span className="agd-mal">Corrige los avisos en rojo para poder crear.</span>}
|
||||
</div>
|
||||
{hayCitas && (
|
||||
<p className="hint">Las visitas se crean con lo básico (fecha, hora, objetivo, oportunidad). Después de crearlas, abre cada una con «abrir en CRM» para agregar el lugar y los participantes.</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{aviso && <p className={aviso.mal ? "agd-mal" : "agd-ok"} role="status">{aviso.texto}</p>}
|
||||
{resultado && (
|
||||
<div className="agd-res">
|
||||
<strong>Tanda #{resultado.loteId}:</strong> {resultado.creadas} creada(s){resultado.errores ? `, ${resultado.errores} con error` : ""}{resultado.omitidas ? `, ${resultado.omitidas} omitida(s)` : ""}.
|
||||
{resultado.resultados.filter((x) => x.estado !== "creada").map((x) => (
|
||||
<div key={x.oppId} className="agd-mal">{x.nombre || x.oppId}: {x.error}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lotes.length > 0 && (
|
||||
<details className="agd-lotes">
|
||||
<summary>Tandas creadas esta semana ({lotes.length})</summary>
|
||||
<ul>
|
||||
{lotes.map((l) => (
|
||||
<li key={l.id}>
|
||||
#{l.id} · {fechaHora(l.creado_en)} · {l.creado_por} · {l.items.filter((x) => x.estado === "creada").length} actividad(es)
|
||||
{l.deshecho_en ? <span> — deshecha {fechaHora(l.deshecho_en)}</span> : (
|
||||
<button type="button" className="agd-btn-sec" disabled={pendiente} onClick={() => deshacer(l.id)} style={{ marginLeft: 8 }}>Deshacer</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
81
app/components/plan/DetalleActividades.js
Normal file
81
app/components/plan/DetalleActividades.js
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
"use client";
|
||||
import { actividadUrl, money } from "../../lib/constants";
|
||||
|
||||
const TIPOS = [
|
||||
["Cita", "Citas"],
|
||||
["Llamada", "Llamadas"],
|
||||
["Tarea", "Tareas"],
|
||||
];
|
||||
const ESTADO_COLOR = {
|
||||
Completada: "var(--gana)",
|
||||
Vencida: "var(--pierde)",
|
||||
Pendiente: "var(--alerta)",
|
||||
Cancelada: "var(--tinta-suave)",
|
||||
};
|
||||
|
||||
// Detalle de TODAS las actividades del período (no solo las del plan), agrupado por tipo y plegado por
|
||||
// defecto: es para consultar o auditar una actividad, no para leerlo de corrido. Solo pantalla.
|
||||
export default function DetalleActividades({ actividades, locked }) {
|
||||
const hay = actividades.length > 0;
|
||||
return (
|
||||
<section className="no-print" style={{ marginTop: 26 }}>
|
||||
<div className="sec-div"><span>Detalle de actividades del período ({actividades.length})</span></div>
|
||||
{!hay && <p className="hint">No hay actividades en este período.</p>}
|
||||
{TIPOS.map(([tipo, plural]) => {
|
||||
const rows = actividades
|
||||
.filter((a) => a.tipo === tipo)
|
||||
.sort((a, b) => (a.scheduledstart || a.scheduledend || "").localeCompare(b.scheduledstart || b.scheduledend || ""));
|
||||
if (!rows.length) return null;
|
||||
const totalIngreso = rows.reduce((s, a) => s + (a.ingresoEstimado || 0), 0);
|
||||
const propioLabel = rows[0]?.campoPropio?.label || "";
|
||||
return (
|
||||
<details className="tw" key={tipo} style={{ marginBottom: 16 }}>
|
||||
<summary className="tw-title" style={{ cursor: "pointer" }}>
|
||||
<span className="tw-chevron">▼</span>
|
||||
<h3>{plural}</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>
|
||||
{rows.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: ESTADO_COLOR[a.estadoFinal] || "var(--tinta-suave)", fontWeight: 700 }}>● {a.estadoFinal}</span>
|
||||
</td>
|
||||
{!locked && <td>{a.owner}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
25
app/components/plan/MrrSegmentos.js
Normal file
25
app/components/plan/MrrSegmentos.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { money } from "../../lib/constants";
|
||||
|
||||
// Tarjeta de KPI con el MRR estimado de cada segmento del plan (Cierre, Negociación, Presentar
|
||||
// oferta, Seguimientos, Renovaciones) — el `subtotal` de cada sección. Compartida por Plan del Día
|
||||
// y Plan de Actividades; va también en el PDF (está dentro de `.plan-kpis`).
|
||||
export default function MrrSegmentos({ secciones, nota }) {
|
||||
const total = secciones.reduce((t, s) => t + (s.subtotal || 0), 0);
|
||||
return (
|
||||
<div className="kpi mrr-seg">
|
||||
<span className="l mrr-seg-t">MRR estimado por segmento{nota ? ` · ${nota}` : ""}</span>
|
||||
<div className="mrr-seg-grid">
|
||||
{secciones.map((s) => (
|
||||
<div key={s.key} className={`mrr-seg-i sec-${s.key}`}>
|
||||
<span className="n">{money(s.subtotal || 0)}</span>
|
||||
<span className="l">{s.titulo}</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="mrr-seg-i mrr-seg-total">
|
||||
<span className="n">{money(total)}</span>
|
||||
<span className="l">Total</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
app/components/plan/PeriodoControles.js
Normal file
43
app/components/plan/PeriodoControles.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"use client";
|
||||
import { useEffect } from "react";
|
||||
import { useRouter, usePathname, useSearchParams } from "next/navigation";
|
||||
import { imprimirPlan } from "./imprimir";
|
||||
|
||||
// Segmentador de período (semana pasada · esta semana · próxima semana · mes pasado · este mes) y
|
||||
// botones de PDF del Plan de Actividades. El período vive en la URL (`periodo`), como el resto de
|
||||
// filtros. El PDF sale del diálogo de impresión del navegador (ver imprimir.js).
|
||||
export default function PeriodoControles({ periodos, periodo, defecto, tituloPdf, tituloPdfEquipo, conEquipo }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
function irA(k) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (k === defecto) params.delete("periodo");
|
||||
else params.set("periodo", k);
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
useEffect(() => () => document.body.classList.remove("plan-print", "plan-print-equipo"), []);
|
||||
|
||||
return (
|
||||
<div className="plan-controles no-print">
|
||||
<div className="seg-tabs" style={{ marginBottom: 0, flexWrap: "wrap" }}>
|
||||
{periodos.map((p) => (
|
||||
<button key={p.k} type="button" className={periodo === p.k ? "on" : ""} onClick={() => irA(p.k)}>
|
||||
{p.lbl}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" className="rep-btn" onClick={() => imprimirPlan({ titulo: tituloPdf })}>
|
||||
🖨 Exportar PDF
|
||||
</button>
|
||||
{conEquipo && (
|
||||
<button type="button" className="rep-btn" onClick={() => imprimirPlan({ titulo: tituloPdfEquipo, equipo: true })}>
|
||||
🖨 PDF del equipo
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
app/components/plan/PlanControles.js
Normal file
58
app/components/plan/PlanControles.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use client";
|
||||
import { useEffect } from "react";
|
||||
import { useRouter, usePathname, useSearchParams } from "next/navigation";
|
||||
import { imprimirPlan } from "./imprimir";
|
||||
|
||||
const addDays = (iso, n) => {
|
||||
const d = new Date(iso + "T12:00:00Z");
|
||||
d.setUTCDate(d.getUTCDate() + n);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
|
||||
// Selector de fecha + botones de PDF del Plan del Día. La fecha vive en la URL (`fecha`), igual que
|
||||
// el resto de filtros, así el enlace se puede compartir. El PDF sale del diálogo de impresión del
|
||||
// navegador (ver imprimir.js).
|
||||
export default function PlanControles({ fecha, hoy, tituloPdf, tituloPdfEquipo, conEquipo }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
function irA(nueva) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (!nueva || nueva === hoy) params.delete("fecha");
|
||||
else params.set("fecha", nueva);
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
// Si por algún motivo el diálogo se cierra sin disparar afterprint, no se deja el modo impresión puesto.
|
||||
useEffect(() => () => document.body.classList.remove("plan-print", "plan-print-equipo"), []);
|
||||
|
||||
return (
|
||||
<div className="plan-controles no-print">
|
||||
<button type="button" className="ag-nav-b" aria-label="Día anterior" onClick={() => irA(addDays(fecha, -1))}>
|
||||
←
|
||||
</button>
|
||||
<input
|
||||
type="date"
|
||||
className="plan-fecha"
|
||||
value={fecha}
|
||||
onChange={(e) => e.target.value && irA(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="ag-nav-b" aria-label="Día siguiente" onClick={() => irA(addDays(fecha, 1))}>
|
||||
→
|
||||
</button>
|
||||
<button type="button" className="ag-nav-b" onClick={() => irA(hoy)} disabled={fecha === hoy}>
|
||||
Hoy
|
||||
</button>
|
||||
<button type="button" className="rep-btn" onClick={() => imprimirPlan({ titulo: tituloPdf })}>
|
||||
🖨 Exportar PDF
|
||||
</button>
|
||||
{conEquipo && (
|
||||
<button type="button" className="rep-btn" onClick={() => imprimirPlan({ titulo: tituloPdfEquipo, equipo: true })}>
|
||||
🖨 PDF del equipo
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
39
app/components/plan/PlanListoBoton.js
Normal file
39
app/components/plan/PlanListoBoton.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
"use client";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { marcarPlanListo } from "../../plan/actions";
|
||||
|
||||
// Botón «Marcar plan como listo» + estado del plan cerrado de ese día. `marca` ya viene formateado
|
||||
// desde el servidor (hora de Nicaragua). Fuera de hoy/futuro solo muestra el estado.
|
||||
export default function PlanListoBoton({ fecha, ownerEmail, nombre, version, marca, puedeMarcar }) {
|
||||
const router = useRouter();
|
||||
const [pendiente, empezar] = useTransition();
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
function marcar() {
|
||||
setError(null);
|
||||
empezar(async () => {
|
||||
const r = await marcarPlanListo(fecha, ownerEmail);
|
||||
if (!r.ok) setError(r.error);
|
||||
else router.refresh();
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="plan-listo no-print">
|
||||
{version ? (
|
||||
<span className="plan-listo-estado ok" title={`Plan de ${nombre}`}>
|
||||
✓ Plan listo · v{version} · {marca}
|
||||
</span>
|
||||
) : (
|
||||
<span className="plan-listo-estado">Plan sin marcar</span>
|
||||
)}
|
||||
{puedeMarcar && (
|
||||
<button type="button" className="rep-btn" onClick={marcar} disabled={pendiente}>
|
||||
{pendiente ? "Guardando…" : version ? "↻ Volver a marcar" : "✓ Marcar plan como listo"}
|
||||
</button>
|
||||
)}
|
||||
{error && <span className="plan-listo-error">{error}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
82
app/components/plan/PlanSeccion.js
Normal file
82
app/components/plan/PlanSeccion.js
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { money, registroUrl } from "../../lib/constants";
|
||||
import { diaCorto } from "../../lib/plan";
|
||||
|
||||
// Una sección del plan (Cierre, Negociación para cierre, Presentar oferta, Seguimientos,
|
||||
// Renovaciones): franja y título del color de la sección + tabla. Compartida por el Plan del Día
|
||||
// (`periodo` falso: una columna «Objetivo del día») y el Plan de Actividades (`periodo` verdadero:
|
||||
// agrega la columna «Días» y el cumplimiento de la sección en el título). Ambas llevan «Tipo
|
||||
// actividad» (Cita, Llamada o Tarea; con la cantidad si una fila tiene varias del mismo tipo).
|
||||
export default function PlanSeccion({ seccion, periodo = false }) {
|
||||
const { key, titulo, sub, filas, subtotal } = seccion;
|
||||
const cols = periodo ? 7 : 6;
|
||||
return (
|
||||
<section className={`plan-sec sec-${key}`}>
|
||||
<div className="plan-sec-head">
|
||||
<h3 className="plan-sec-t">{titulo}</h3>
|
||||
<span className="plan-sec-cnt">
|
||||
{filas.length} {filas.length === 1 ? "cliente" : "clientes"} · {money(subtotal)}
|
||||
{periodo && filas.length > 0 ? ` · ${seccion.actHechas} de ${seccion.actTotal} completadas` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="plan-sec-sub no-print">{sub}</div>
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th>
|
||||
<th>Cliente</th>
|
||||
<th>{periodo ? "Objetivos" : "Objetivo del día"}</th>
|
||||
<th>Tipo actividad</th>
|
||||
{periodo && <th>Días</th>}
|
||||
<th className="num">Valor estimado</th>
|
||||
<th className="plan-estado">Estado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filas.length ? (
|
||||
filas.map((r) => (
|
||||
<tr key={r.key} className={r.estado === "Completada" ? "plan-hecha" : r.estado === "Vencida" ? "plan-venc" : ""}>
|
||||
<td>{r.owner}</td>
|
||||
<td>
|
||||
<a className="opp" href={registroUrl(r.opp.etn, r.opp.id)} target="_blank" rel="noopener">
|
||||
{r.opp.cliente || r.opp.nombre || "—"}
|
||||
</a>
|
||||
{r.opp.etn === "incident" && <span className="plan-ref"> (caso)</span>}
|
||||
{r.opp.etn === "account" && <span className="plan-ref"> (cuenta)</span>}
|
||||
</td>
|
||||
<td>{r.objetivos.join(" · ")}</td>
|
||||
<td>{r.tipos.map((t) => (t.n > 1 ? `${t.tipo} (${t.n})` : t.tipo)).join(" · ")}</td>
|
||||
{periodo && (
|
||||
<td className="plan-dias">
|
||||
{r.dias.map((d) => (
|
||||
<span className="plan-dia-chip" key={d}>{diaCorto(d)}</span>
|
||||
))}
|
||||
</td>
|
||||
)}
|
||||
<td className="num">{r.opp.valor == null ? "—" : money(r.opp.valor)}</td>
|
||||
<td className="plan-estado">
|
||||
{r.estado === "Completada" ? "✓ Completada" : r.estado}
|
||||
{r.total > 1 ? ` (${r.hechas}/${r.total})` : ""}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={cols} className="plan-vacio">Sin actividades agendadas</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
{filas.length > 0 && (
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan={periodo ? 5 : 4} className="num"><strong>Total {titulo.toLowerCase()}</strong></td>
|
||||
<td className="num"><strong>{money(subtotal)}</strong></td>
|
||||
<td />
|
||||
</tr>
|
||||
</tfoot>
|
||||
)}
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
90
app/components/plan/PlanVsReal.js
Normal file
90
app/components/plan/PlanVsReal.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import Link from "next/link";
|
||||
import { SECCIONES } from "../../lib/plan";
|
||||
import { registroUrl, money } from "../../lib/constants";
|
||||
|
||||
const tituloSec = Object.fromEntries(SECCIONES.map((s) => [s.key, s.titulo]));
|
||||
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
||||
|
||||
function claseRes(res) {
|
||||
if (res === "Cumplida") return "ok";
|
||||
if (res === "No cumplida") return "mal";
|
||||
if (res === "Reprogramada") return "rep";
|
||||
if (res.startsWith("Agregada")) return "add";
|
||||
if (res === "Cancelada" || res === "Eliminada") return "baja";
|
||||
return "pen";
|
||||
}
|
||||
|
||||
// Vista de coaching: la foto del plan cerrado contra lo que realmente pasó con cada actividad.
|
||||
// Solo pantalla (no va en el PDF). Server component: sin estado propio; las versiones se eligen
|
||||
// con `?version=` en la URL.
|
||||
export default function PlanVsReal({ foto, versiones, cmp, nombre, marca, hrefVersion }) {
|
||||
const { resumen, lineas, agregadas } = cmp;
|
||||
const pct = resumen.enFoto ? ((resumen.cumplidas / resumen.enFoto) * 100).toFixed(1) : "0.0";
|
||||
const filas = [...lineas, ...agregadas];
|
||||
return (
|
||||
<section className="panel plan-vs no-print">
|
||||
<h3>Plan cerrado vs. lo que pasó — {nombre}</h3>
|
||||
<p className="hint">
|
||||
Foto del plan del {fechaTxt(foto.fecha)} marcada {marca} (v{foto.version}) por {foto.marcado_por}.
|
||||
{versiones.length > 1 && (
|
||||
<>
|
||||
{" "}Versiones:{" "}
|
||||
{versiones.map((v, i) => (
|
||||
<span key={v.version}>
|
||||
{i > 0 && " · "}
|
||||
{v.version === foto.version ? <strong>v{v.version}</strong> : <Link href={hrefVersion(v.version)}>v{v.version}</Link>}
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className="kpis plan-vs-kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{pct}%</span>
|
||||
<span className="l">Cumplimiento del plan ({resumen.cumplidas} de {resumen.enFoto})</span>
|
||||
</div>
|
||||
<div className="kpi"><span className="n">{resumen.noCumplidas}</span><span className="l">No cumplidas</span></div>
|
||||
<div className="kpi"><span className="n">{resumen.reprogramadas}</span><span className="l">Reprogramadas</span></div>
|
||||
<div className="kpi"><span className="n">{resumen.canceladas}</span><span className="l">Canceladas o eliminadas</span></div>
|
||||
<div className="kpi">
|
||||
<span className="n">{resumen.agregadas}</span>
|
||||
<span className="l">Agregadas después{resumen.agregadas ? ` (${resumen.agregadasCumplidas} cumplidas)` : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Sección</th>
|
||||
<th>Cliente</th>
|
||||
<th>Actividad</th>
|
||||
<th>Objetivo</th>
|
||||
<th className="num">Valor estimado</th>
|
||||
<th>Resultado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filas.map((l, i) => (
|
||||
<tr key={`${l.id}-${i}`}>
|
||||
<td>{tituloSec[l.sec] || l.sec}</td>
|
||||
<td>
|
||||
<a className="opp" href={registroUrl(l.etn, l.id)} target="_blank" rel="noopener">{l.cliente || "—"}</a>
|
||||
</td>
|
||||
<td>{l.tipo} · {l.asunto}</td>
|
||||
<td>{l.objetivo || "(sin objetivo)"}</td>
|
||||
<td className="num">{l.valor == null ? "—" : money(l.valor)}</td>
|
||||
<td>
|
||||
<span className={`plan-res ${claseRes(l.res)}`}>
|
||||
{l.res}{l.detalle ? ` → ${fechaTxt(l.detalle)}` : ""}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
119
app/components/plan/SinActividadPanel.js
Normal file
119
app/components/plan/SinActividadPanel.js
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { money, registroUrl, nuevaActividadUrl, TIPOS_NUEVA_ACTIVIDAD } from "../../lib/constants";
|
||||
import { COD_RENOVACION, objetivoSugerido } from "../../lib/plan";
|
||||
|
||||
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
||||
|
||||
// Huecos de planificación: oportunidades con cierre estimado en el período y sin actividad agendada,
|
||||
// con un botón por tipo (Tarea / Cita / Llamada) que abre el formulario nuevo en Dynamics ya ligado a
|
||||
// la oportunidad. Solo pantalla (no va en el PDF). Compartido por Plan del Día y Plan de Actividades.
|
||||
const tipoDe = (o) => (COD_RENOVACION.has(o.tipoCodigo) ? "Renovación" : "Venta");
|
||||
const pctDe = (o) => parseInt(o.forecast || "", 10) || 0;
|
||||
const CLAVES = {
|
||||
tipo: (o) => tipoDe(o),
|
||||
valor: (o) => o.valor || 0,
|
||||
forecast: (o) => pctDe(o),
|
||||
};
|
||||
|
||||
// Encabezado ordenable: 1.er clic = descendente (↓ mayor primero), 2.º = ascendente, 3.º = vuelve al orden por prioridad.
|
||||
function Th({ col, orden, setOrden, className, children }) {
|
||||
const activo = orden.col === col;
|
||||
const flecha = activo ? (orden.dir === "desc" ? " ▼" : " ▲") : " ↕";
|
||||
const siguiente = () => setOrden(!activo ? { col, dir: "desc" } : orden.dir === "desc" ? { col, dir: "asc" } : { col: null, dir: "desc" });
|
||||
return (
|
||||
<th className={className} aria-sort={activo ? (orden.dir === "desc" ? "descending" : "ascending") : "none"}>
|
||||
<button type="button" onClick={siguiente} style={{ all: "unset", cursor: "pointer", fontWeight: "inherit" }} title="Clic para ordenar de mayor a menor, de menor a mayor o volver al orden original">
|
||||
{children}
|
||||
<span style={{ opacity: activo ? 1 : 0.4 }}>{flecha}</span>
|
||||
</button>
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SinActividadPanel({ filas, titulo, hint, vacio, nota }) {
|
||||
const [orden, setOrden] = useState({ col: null, dir: "desc" });
|
||||
const [tipo, setTipo] = useState("todos");
|
||||
|
||||
const visibles = useMemo(() => {
|
||||
let r = tipo === "todos" ? filas : filas.filter((o) => tipoDe(o) === tipo);
|
||||
if (orden.col) {
|
||||
const k = CLAVES[orden.col];
|
||||
const m = orden.dir === "desc" ? -1 : 1;
|
||||
r = [...r].sort((a, b) => {
|
||||
const x = k(a), y = k(b);
|
||||
return (typeof x === "string" ? x.localeCompare(y, "es") : x - y) * m;
|
||||
});
|
||||
}
|
||||
return r;
|
||||
}, [filas, orden, tipo]);
|
||||
|
||||
return (
|
||||
<section className="panel plan-sin no-print">
|
||||
<h3>{titulo} ({tipo === "todos" ? filas.length : `${visibles.length} de ${filas.length}`})</h3>
|
||||
<p className="hint">{hint}</p>
|
||||
{nota && <p className="hint plan-sin-nota">{nota}</p>}
|
||||
{filas.length > 0 && (
|
||||
<p className="hint" style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||
<label htmlFor="sin-tipo">Mostrar tipo:</label>
|
||||
<select id="sin-tipo" value={tipo} onChange={(e) => setTipo(e.target.value)}>
|
||||
<option value="todos">Todos</option>
|
||||
<option value="Venta">Venta</option>
|
||||
<option value="Renovación">Renovación</option>
|
||||
</select>
|
||||
<span>· Clic en Tipo, Valor estimado o Forecast para ordenar</span>
|
||||
</p>
|
||||
)}
|
||||
{filas.length ? (
|
||||
<div className="ts" style={{ maxHeight: 460, overflowY: "auto" }}>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th>
|
||||
<th>Cliente</th>
|
||||
<Th col="tipo" orden={orden} setOrden={setOrden}>Tipo</Th>
|
||||
<Th col="valor" orden={orden} setOrden={setOrden} className="num">Valor estimado</Th>
|
||||
<th>Cierre estimado</th>
|
||||
<Th col="forecast" orden={orden} setOrden={setOrden}>Forecast</Th>
|
||||
<th>Objetivo sugerido</th>
|
||||
<th>Agendar</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visibles.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.owner}</td>
|
||||
<td>
|
||||
<a className="opp" href={registroUrl("opportunity", o.id)} target="_blank" rel="noopener">
|
||||
{o.cliente || o.nombre || "—"}
|
||||
</a>
|
||||
{o.prioridadAlta && <span className="plan-prio" title="Forecast 80% o 90%: lo más cercano al cierre">Prioridad</span>}
|
||||
</td>
|
||||
<td>{tipoDe(o)}</td>
|
||||
<td className="num">{money(o.valor)}</td>
|
||||
<td>{fechaTxt(o.cierre)}</td>
|
||||
<td>{o.forecast || "—"}</td>
|
||||
<td className="plan-sugerido" title="Guía según la etapa de forecast; al agendar, elige este objetivo en la actividad">
|
||||
{objetivoSugerido(o) || "—"}
|
||||
</td>
|
||||
<td>
|
||||
<span className="plan-agenda-btns">
|
||||
{TIPOS_NUEVA_ACTIVIDAD.map((t) => (
|
||||
<a key={t.etn} className="plan-agendar" href={nuevaActividadUrl(o, t.etn)} target="_blank" rel="noopener" title={t.ayuda}>
|
||||
+ {t.label}
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="hint" style={{ margin: 0 }}>✓ {vacio}</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
23
app/components/plan/imprimir.js
Normal file
23
app/components/plan/imprimir.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// Impresión / PDF de las páginas de plan (Plan del Día y Plan de Actividades): diálogo de impresión del
|
||||
// navegador ("Guardar como PDF"), sin librería. Agrega `body.plan-print` (y `plan-print-equipo` para
|
||||
// el PDF del equipo) — layout.css oculta menú y controles y compacta las tablas —, cambia
|
||||
// `document.title` (el navegador lo usa de nombre de archivo) e inyecta una hoja Carta (Letter)
|
||||
// horizontal solo mientras imprime. Todo se revierte al terminar (`afterprint`).
|
||||
export function imprimirPlan({ titulo, equipo = false }) {
|
||||
const tituloPrevio = document.title;
|
||||
document.title = titulo;
|
||||
document.body.classList.add("plan-print");
|
||||
if (equipo) document.body.classList.add("plan-print-equipo");
|
||||
const hoja = document.createElement("style");
|
||||
hoja.id = "plan-hoja";
|
||||
hoja.textContent = "@page{size:letter landscape;margin:8mm 9mm;}";
|
||||
document.head.appendChild(hoja);
|
||||
const limpiar = () => {
|
||||
document.body.classList.remove("plan-print", "plan-print-equipo");
|
||||
document.title = tituloPrevio;
|
||||
document.getElementById("plan-hoja")?.remove();
|
||||
window.removeEventListener("afterprint", limpiar);
|
||||
};
|
||||
window.addEventListener("afterprint", limpiar);
|
||||
window.print();
|
||||
}
|
||||
70
app/components/tendencia/BucketTabs.js
Normal file
70
app/components/tendencia/BucketTabs.js
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
"use client";
|
||||
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||
import { money } from "../../lib/constants";
|
||||
|
||||
// Gráfico de evolución simplificado — puerto de tendChart() (assets/js/pages/tendencia.js) sin el
|
||||
// SVG con gradientes/patrones: una fila de barra por mes, con la meta marcada como línea punteada
|
||||
// dentro de la barra. Clic en un mes lo aísla en toda la página (searchParam `t`); clic de nuevo lo
|
||||
// quita — mismo criterio "todo o nada" que el resto del cross-filter de la app.
|
||||
export default function BucketTabs({ buckets }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const sel = searchParams.get("t");
|
||||
const maxV = Math.max(...buckets.map((b) => Math.max(b.sumW, b.meta || 0)), 1);
|
||||
|
||||
function toggle(mes) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (sel === mes) params.delete("t");
|
||||
else params.set("t", mes);
|
||||
const qs = params.toString();
|
||||
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="panel">
|
||||
<h3>Evolución del ingreso ganado</h3>
|
||||
<p className="hint">
|
||||
Clic en un mes para aislarlo · línea punteada = meta
|
||||
</p>
|
||||
{buckets.map((b) => {
|
||||
const active = sel === b.mes;
|
||||
return (
|
||||
<div
|
||||
key={b.mes}
|
||||
className={`row static${active ? " active" : ""}`}
|
||||
style={{ cursor: "pointer", ...(active ? { background: "var(--gana-soft)" } : {}) }}
|
||||
onClick={() => toggle(b.mes)}
|
||||
>
|
||||
<div className="bl">
|
||||
<span className="nm">
|
||||
{b.lbl}
|
||||
{b.enCurso ? " · en curso" : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="bar-cell">
|
||||
<div
|
||||
className="bar-fill"
|
||||
style={{ width: `${Math.min(100, (b.sumW / maxV) * 100).toFixed(1)}%`, opacity: b.enCurso ? 0.6 : 1 }}
|
||||
/>
|
||||
{b.meta ? (
|
||||
<div
|
||||
title={`Meta: ${money(b.meta)}`}
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: `${Math.min(100, (b.meta / maxV) * 100).toFixed(1)}%`,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
borderLeft: "2px dashed var(--pierde)",
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="v">{b.won}</span>
|
||||
<span className="c">{money(b.sumW)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/detalle/loading.js
Normal file
4
app/detalle/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
153
app/detalle/page.js
Normal file
153
app/detalle/page.js
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import Link from "next/link";
|
||||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getPipeline, getClosed, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { PLAN_ORDER } from "../lib/derive";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import PlanFilterSelect from "../components/PlanFilterSelect";
|
||||
import { DYN, ACT_COLOR, money2 } from "../lib/constants";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
const SETS = [
|
||||
{ key: "pipe", label: "Tubería activa" },
|
||||
{ key: "ganadas", label: "Ganadas" },
|
||||
{ key: "perdidas", label: "Perdidas" },
|
||||
];
|
||||
|
||||
export default async function DetallePage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const { owner, set, plan } = await searchParams;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const detSet = SETS.some((s) => s.key === set) ? set : "pipe";
|
||||
const mes = currentMonth();
|
||||
|
||||
let rows;
|
||||
try {
|
||||
if (detSet === "pipe") {
|
||||
rows = await getPipeline(session.accessToken, scope);
|
||||
} else {
|
||||
const statecode = detSet === "ganadas" ? 1 : 2;
|
||||
rows = await getClosed(session.accessToken, scope, statecode, mes, undefined, VENTA_TYPE_FILTER);
|
||||
}
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
// Cerradas: la fase final del embudo es el resultado (Ganada / Perdida).
|
||||
if (detSet !== "pipe") rows = rows.map((o) => ({ ...o, faseActual: detSet === "ganadas" ? "Ganada" : "Perdida" }));
|
||||
const planesDisponibles = detSet === "pipe" ? PLAN_ORDER.filter((p) => rows.some((o) => (o.plan || "Sin plan de cierre") === p)) : [];
|
||||
const filtrados = detSet === "pipe" && plan ? rows.filter((o) => (o.plan || "Sin plan de cierre") === plan) : rows;
|
||||
const sorted = [...filtrados].sort((a, b) => (b.est ?? b.actual ?? 0) - (a.est ?? a.actual ?? 0));
|
||||
|
||||
const qs = (key) => {
|
||||
const p = new URLSearchParams();
|
||||
if (owner) p.set("owner", owner);
|
||||
p.set("set", key);
|
||||
return `/detalle?${p.toString()}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Detalle</h2>
|
||||
|
||||
<div className="seg-tabs" style={{ marginBottom: 16 }}>
|
||||
{SETS.map((s) => (
|
||||
<Link key={s.key} href={qs(s.key)} className={detSet === s.key ? "on" : ""}>
|
||||
<button className={detSet === s.key ? "on" : ""} type="button">
|
||||
{s.label}
|
||||
</button>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{detSet === "pipe" && planesDisponibles.length > 0 && (
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<PlanFilterSelect options={planesDisponibles} current={plan} baseHref={qs("pipe")} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="hint" style={{ marginBottom: 12 }}>
|
||||
{sorted.length} oportunidades{detSet !== "pipe" ? ` (${mes})` : ""}
|
||||
</p>
|
||||
|
||||
{sorted.length === 0 ? (
|
||||
<p>No hay oportunidades para este filtro.</p>
|
||||
) : (
|
||||
<div className="tw">
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Seg.</th>
|
||||
{!scope.locked && <th>Ejecutivo</th>}
|
||||
{detSet === "pipe" ? (
|
||||
<>
|
||||
<th>Plan cierre</th>
|
||||
<th>Fase actual</th>
|
||||
<th>Actividad</th>
|
||||
<th className="num">MRR est.</th>
|
||||
<th className="num">Forecast</th>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<th>Tipo</th>
|
||||
<th className="num">MRR</th>
|
||||
<th>Cierre</th>
|
||||
</>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td>
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||
{o.name}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||
</span>
|
||||
</td>
|
||||
{!scope.locked && <td>{o.owner}</td>}
|
||||
{detSet === "pipe" ? (
|
||||
<>
|
||||
<td>{(o.plan || "").replace(" - ", " ")}</td>
|
||||
<td>{o.faseActual || "—"}</td>
|
||||
<td>
|
||||
<span style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }}>
|
||||
● {o.actividad}
|
||||
</span>
|
||||
</td>
|
||||
<td className="num">{money2(o.est)}</td>
|
||||
<td className="num">{money2(o.fc)}</td>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<td>{o.tipo}</td>
|
||||
<td className="num">{money2(o.actual)}</td>
|
||||
<td>{o.actualClose || "—"}</td>
|
||||
</>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
34
app/diagnostico/page.js
Normal file
34
app/diagnostico/page.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { dv } from "../lib/dataverse";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function checkDataverse(accessToken) {
|
||||
try {
|
||||
const data = await dv("systemusers?$select=fullname&$top=1", accessToken);
|
||||
return { ok: true, sample: data.value?.[0]?.fullname };
|
||||
} catch (e) {
|
||||
return { ok: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
export default async function DiagnosticoPage() {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const check = session.accessToken ? await checkDataverse(session.accessToken) : { ok: false, error: "sin accessToken" };
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Diagnóstico</h2>
|
||||
<ul>
|
||||
<li><strong>Correo:</strong> {session.email}</li>
|
||||
<li><strong>Rol:</strong> {session.isAdmin ? "Administrador" : "Vendedor"}</li>
|
||||
<li><strong>Token de Dataverse:</strong> {check.ok ? "✅ funciona" : `❌ ${check.error}`}</li>
|
||||
{check.ok && <li><strong>Prueba de lectura:</strong> {check.sample}</li>}
|
||||
{session.error && <li style={{ color: "red" }}><strong>Error de sesión:</strong> {session.error}</li>}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/ganadas/loading.js
Normal file
4
app/ganadas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
188
app/ganadas/page.js
Normal file
188
app/ganadas/page.js
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getClosedRange, getSystemUsers, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { agg, EJECUTIVOS_VENTA, PROPIETARIOS_VENTA } from "../lib/derive";
|
||||
import { PERIODOS, periodoActivo, rangoDePeriodo } from "../lib/periodos";
|
||||
import { getMetas, getMetaGlobal } from "../lib/metas";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import SegTabs from "../components/SegTabs";
|
||||
import Panel from "../components/pipeline/Panel";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import { DYN, money, money2 } from "../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DIM_LABELS = { tipo: "Tipo", linea: "Línea", origen: "Origen", campaign: "Campaña" };
|
||||
|
||||
export default async function GanadasPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const periodo = periodoActivo(sp.periodo);
|
||||
const { from, to, lbl: periodoLbl, mensual } = rangoDePeriodo(periodo);
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
let wonAll, lostAll, allUsers;
|
||||
try {
|
||||
[wonAll, lostAll, allUsers] = await Promise.all([
|
||||
getClosedRange(session.accessToken, scope, 1, from, to, undefined, VENTA_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, scope, 2, from, to, undefined, VENTA_TYPE_FILTER),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
|
||||
const won = applyFilt(wonAll, filt);
|
||||
const lost = applyFilt(lostAll, filt);
|
||||
|
||||
const metas = getMetas();
|
||||
const metaGlobal = getMetaGlobal();
|
||||
|
||||
const sumW = won.reduce((a, o) => a + (o.actual || 0), 0);
|
||||
const arpu = won.length ? sumW / won.length : 0;
|
||||
const conv = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
|
||||
// Cumplimiento compara contra meta MENSUAL — solo tiene sentido en "este mes"/"mes anterior".
|
||||
const cumplGlobal = mensual && metaGlobal ? Math.round((sumW / metaGlobal) * 100) : null;
|
||||
|
||||
const porEjecutivo = EJECUTIVOS_VENTA.map((nombre) => {
|
||||
const w = won.filter((o) => o.owner === nombre);
|
||||
const logrado = w.reduce((a, o) => a + (o.actual || 0), 0);
|
||||
const email = allUsers.find((u) => u.name === nombre)?.email;
|
||||
const meta = email ? metas[email] : null;
|
||||
const pct = mensual && meta ? Math.round((logrado / meta) * 100) : null;
|
||||
return { nombre, logrado, meta, pct };
|
||||
}).sort((a, b) => (b.pct ?? -1) - (a.pct ?? -1));
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Ventas Ganadas</h2>
|
||||
<OwnerControl
|
||||
owners={owners}
|
||||
current={scope.locked ? [session.email] : scope.emails}
|
||||
locked={scope.locked}
|
||||
lockedLabel={session.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={PERIODOS} activeKey={periodo} paramName="periodo" />
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{money2(sumW)}</span>
|
||||
<span className="l">Suma ingresos reales</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{won.length}</span>
|
||||
<span className="l">Oportunidades ganadas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money2(arpu)}</span>
|
||||
<span className="l">ARPU logrado</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{conv}%</span>
|
||||
<span className="l">% Conversión</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={cumplGlobal != null && cumplGlobal < 70 ? "n pierde" : "n"}>
|
||||
{cumplGlobal != null ? `${cumplGlobal}%` : "n/d"}
|
||||
</span>
|
||||
<span className="l">Cumplimiento equipo{!mensual ? " (n/d — meta es mensual)" : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="panel">
|
||||
<h3>Cumplimiento de meta por ejecutivo</h3>
|
||||
<p className="hint">
|
||||
Ingresos reales ÷ meta mensual · verde ≥70% · ámbar 50-69% · rojo <50%
|
||||
{!mensual ? " · n/d fuera de \"Este mes\"/\"Mes anterior\"" : ""}
|
||||
</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">
|
||||
{money(r.logrado)}
|
||||
{r.meta ? `/${money(r.meta)}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="grid2">
|
||||
<Panel title="Por Tipo de Oportunidad" rows={agg(won, "tipo", (o) => o.actual)} dimKey="tipo" />
|
||||
<Panel title="Por Línea de Negocio" rows={agg(won, "linea", (o) => o.actual)} dimKey="linea" />
|
||||
<Panel title="Por Origen" rows={agg(won, "origen", (o) => o.actual)} dimKey="origen" />
|
||||
<Panel title="Por Campaña de Origen" rows={agg(won, "campaign", (o) => o.actual)} top={7} dimKey="campaign" />
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Detalle de oportunidades ganadas</h3>
|
||||
</div>
|
||||
{won.length === 0 ? (
|
||||
<p>No hay oportunidades ganadas en este período para este filtro.</p>
|
||||
) : (
|
||||
<div className="tw">
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Seg.</th>
|
||||
{!scope.locked && <th>Ejecutivo</th>}
|
||||
<th>Tipo</th>
|
||||
<th>Línea de Negocio</th>
|
||||
<th>Origen</th>
|
||||
<th className="num">MRR</th>
|
||||
<th>Cierre</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...won].sort((a, b) => b.actual - a.actual).map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td>
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||
{o.name}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||
</span>
|
||||
</td>
|
||||
{!scope.locked && <td>{o.owner}</td>}
|
||||
<td>{o.tipo}</td>
|
||||
<td>{o.linea}</td>
|
||||
<td>{o.origen}</td>
|
||||
<td className="num">{money2(o.actual)}</td>
|
||||
<td>{o.actualClose || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
10
app/globals.css
Normal file
10
app/globals.css
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
.login-btn {
|
||||
font-family: var(--sans);
|
||||
font-size: 13px;
|
||||
padding: 7px 14px;
|
||||
border: 1px solid var(--marca);
|
||||
border-radius: 6px;
|
||||
background: var(--marca);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
5
app/icon.svg
Normal file
5
app/icon.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<svg width="64" height="64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="64" height="64" rx="14" fill="#01205B"/>
|
||||
<text x="32" y="43" font-family="Arial, Helvetica, sans-serif" font-size="30" font-weight="700"
|
||||
fill="#ffffff" text-anchor="middle">A+</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 299 B |
71
app/layout.js
Normal file
71
app/layout.js
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import "./globals.css";
|
||||
import { auth, signIn, signOut } from "./lib/auth";
|
||||
import AppShell from "./components/AppShell";
|
||||
|
||||
export const metadata = {
|
||||
title: "Informe Comercial ALFA+",
|
||||
description: "Analítica comercial en vivo sobre Dynamics 365",
|
||||
};
|
||||
|
||||
// Mismo orden y agrupación que assets/js/utils.js del sitio HTML — no reordenar sin actualizar
|
||||
// también ese archivo, se desincronizan los dos diseños.
|
||||
const PAGES = [
|
||||
{ href: "/", label: "Agenda", ico: "🗓", grupo: "Actividades", built: true },
|
||||
{ href: "/plan", label: "Plan del Día", ico: "☀", grupo: "Actividades", built: true },
|
||||
{ href: "/actividades", label: "Plan de Actividades", ico: "✓", grupo: "Actividades", built: true },
|
||||
|
||||
{ href: "/prevision", label: "Previsión de Ventas", ico: "◎", grupo: "Ventas", built: true },
|
||||
{ href: "/tuberia", label: "Tubería de Ventas", ico: "▤", grupo: "Ventas", built: true },
|
||||
{ href: "/resumen", label: "Ventas Resumen", ico: "▣", grupo: "Ventas", built: true },
|
||||
{ href: "/ganadas", label: "Oportunidades Ganadas", ico: "▲", grupo: "Ventas", built: true },
|
||||
{ href: "/perdemos", label: "Oportunidades Perdidas", ico: "▼", grupo: "Ventas", built: true },
|
||||
{ href: "/tendencia", label: "Tendencia", ico: "📈", grupo: "Ventas", built: true },
|
||||
|
||||
{ href: "/renovaciones/prevision", label: "Previsión de Renovaciones", ico: "◍", grupo: "Renovaciones", built: true },
|
||||
{ href: "/renovaciones/tuberia", label: "Tubería de Renovaciones", ico: "▥", grupo: "Renovaciones", built: true },
|
||||
{ href: "/renovaciones/logradas", label: "Renovaciones Logradas", ico: "♻", grupo: "Renovaciones", built: true },
|
||||
{ href: "/renovaciones/perdidas", label: "Renovaciones Perdidas", ico: "✖", grupo: "Renovaciones", built: true },
|
||||
|
||||
{ href: "/nuevas", label: "Cohorte de Oportunidades", ico: "◔", grupo: "Análisis", built: true },
|
||||
{ href: "/mapa", label: "Mapa Geográfico", ico: "◈", grupo: "Análisis", built: false },
|
||||
{ href: "/precio", label: "Precio por Mbps", ico: "⊟", grupo: "Análisis", built: false },
|
||||
{ href: "/detalle", label: "Detalle", ico: "☰", grupo: "Análisis", built: true },
|
||||
];
|
||||
|
||||
export default async function RootLayout({ children }) {
|
||||
const session = await auth();
|
||||
// Se recalcula en cada request porque las páginas hijas son force-dynamic (sin caché) — sirve
|
||||
// para confirmar a simple vista que "en vivo" no es un texto estático.
|
||||
const generatedAt = new Date().toISOString();
|
||||
|
||||
async function handleSignIn() {
|
||||
"use server";
|
||||
await signIn("microsoft-entra-id");
|
||||
}
|
||||
|
||||
async function handleSignOut() {
|
||||
"use server";
|
||||
await signOut();
|
||||
}
|
||||
|
||||
return (
|
||||
<html lang="es">
|
||||
<head>
|
||||
<link rel="stylesheet" href="/assets/css/base.css" />
|
||||
<link rel="stylesheet" href="/assets/css/layout.css" />
|
||||
<link rel="stylesheet" href="/assets/css/components.css" />
|
||||
</head>
|
||||
<body>
|
||||
<AppShell
|
||||
pages={PAGES}
|
||||
session={session?.email ? { email: session.email, isAdmin: session.isAdmin } : null}
|
||||
onSignIn={handleSignIn}
|
||||
onSignOut={handleSignOut}
|
||||
generatedAt={generatedAt}
|
||||
>
|
||||
{children}
|
||||
</AppShell>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
194
app/lib/agendador.js
Normal file
194
app/lib/agendador.js
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
// Agendador sugerido de la semana — configuración y lógica PURA (sin Dynamics ni React), compartida
|
||||
// por la pantalla (cliente) y las acciones de servidor, que vuelven a validar todo antes de crear.
|
||||
// Diseño y decisiones: Proyectos/Análisis e Informes/Analitica de CRM/agendador-automatico-diseno.md
|
||||
import { actAncla } from "./derive";
|
||||
|
||||
export const AGENDADOR = {
|
||||
// PILOTO (2026-10-27): solo estos ejecutivos tienen agendador. Para ampliarlo, agregar correos aquí.
|
||||
piloto: ["maria.marenco@alfa.com.ni"],
|
||||
// Asistente de ventas: puede ver y agendar para los ejecutivos del piloto (no es administrador).
|
||||
asistentes: ["ashley.bermudez@alfa.com.ni"],
|
||||
// Máximo por día, por tipo. Llamadas y visitas (citas) las fijó Marco; el de tareas es un supuesto.
|
||||
topes: { Llamada: 6, Cita: 3, Tarea: 6 },
|
||||
// Horario (hora de Nicaragua, minutos desde las 00:00), de lunes a viernes: 9:00–12:00 y 14:00–16:00.
|
||||
franjas: [[540, 720], [840, 960]],
|
||||
duracion: { Llamada: 30, Cita: 60 }, // minutos
|
||||
paso: 30, // las horas de inicio salen cada 30 min
|
||||
horaTarea: 960, // las tareas vencen a las 16:00 del día elegido
|
||||
};
|
||||
|
||||
export const TIPOS_AGENDADOR = ["Llamada", "Cita", "Tarea"];
|
||||
export const ENTIDAD_TIPO = { Llamada: "phonecalls", Cita: "appointments", Tarea: "tasks" };
|
||||
// Objetivos que ofrece el agendador (nombres del catálogo `alfa_objetivosdeactividades`).
|
||||
export const OBJETIVOS_AGENDADOR = [
|
||||
"Calificar Oportunidad",
|
||||
"Diagnosticar Necesidades",
|
||||
"Presentación de Servicio",
|
||||
"Presentar Oferta",
|
||||
"Negociación",
|
||||
"Firma Contrato-Adendum",
|
||||
"Renovación",
|
||||
];
|
||||
|
||||
const OFFSET_MS = 6 * 3600 * 1000; // Nicaragua = UTC-6 todo el año
|
||||
|
||||
export const minAHora = (m) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
|
||||
export const horaAMin = (h) => {
|
||||
const m = /^(\d{2}):(\d{2})$/.exec(h || "");
|
||||
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
|
||||
};
|
||||
|
||||
// Hora local (Nicaragua) de un instante ISO: { dia: "YYYY-MM-DD", min }.
|
||||
export function localDeIso(iso) {
|
||||
const d = new Date(new Date(iso).getTime() - OFFSET_MS);
|
||||
return { dia: d.toISOString().slice(0, 10), min: d.getUTCHours() * 60 + d.getUTCMinutes() };
|
||||
}
|
||||
|
||||
// Fecha y hora de Nicaragua → instante ISO en UTC (lo que espera Dynamics).
|
||||
export const aUtc = (dia, hora) => new Date(`${dia}T${hora}:00-06:00`).toISOString();
|
||||
|
||||
// Horas de inicio posibles de un tipo (Tarea no tiene hora: vence a las 16:00).
|
||||
export function horasDe(tipo) {
|
||||
if (tipo === "Tarea") return [];
|
||||
const dur = AGENDADOR.duracion[tipo];
|
||||
const out = [];
|
||||
for (const [a, b] of AGENDADOR.franjas) for (let s = a; s + dur <= b; s += AGENDADOR.paso) out.push(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
// De las actividades del ejecutivo (no canceladas) saca, por día: cuántas hay de cada tipo (para los
|
||||
// topes) y los bloques de tiempo ocupados por llamadas y citas (para no encimar horarios).
|
||||
// `acts`: [{ tipo, estado, scheduledstart, scheduledend }].
|
||||
export function resumenExistentes(acts) {
|
||||
const existentes = {};
|
||||
const bloques = {};
|
||||
for (const a of acts || []) {
|
||||
if (a.estado === "cancelada" || !TIPOS_AGENDADOR.includes(a.tipo)) continue;
|
||||
const anc = actAncla(a);
|
||||
if (!anc) continue;
|
||||
const { dia } = localDeIso(anc);
|
||||
(existentes[dia] ||= { Llamada: 0, Cita: 0, Tarea: 0 })[a.tipo]++;
|
||||
if (a.tipo !== "Tarea" && a.scheduledstart && a.scheduledend) {
|
||||
const i = localDeIso(a.scheduledstart);
|
||||
const f = localDeIso(a.scheduledend);
|
||||
if (i.dia === f.dia && f.min > i.min) (bloques[i.dia] ||= []).push([i.min, f.min]);
|
||||
}
|
||||
}
|
||||
return { existentes, bloques };
|
||||
}
|
||||
|
||||
const cuentaVacia = () => ({ Llamada: 0, Cita: 0, Tarea: 0 });
|
||||
const total = (c) => c.Llamada + c.Cita + c.Tarea;
|
||||
const libre = (bl, s, dur) => !(bl || []).some(([a, b]) => s < b && s + dur > a);
|
||||
|
||||
// Reparte los candidatos en los días de la semana. Los más prioritarios (forecast 80/90, luego mayor
|
||||
// valor) se colocan primero y caen en los días más tempranos y con menos carga; las llamadas y citas
|
||||
// se acomodan en la primera hora libre del horario permitido. Los que no caben quedan sin día
|
||||
// (`sinCupo`). `dias`: días hábiles permitidos; `ahoraMin`: hora actual (si `hoy` está en `dias`, no
|
||||
// se agenda antes de ahora + 30 min).
|
||||
export function proponer({ candidatos, dias, existentes, bloques, hoy, ahoraMin, tipo = "Llamada" }) {
|
||||
const cuenta = {};
|
||||
const ocup = {};
|
||||
dias.forEach((d) => {
|
||||
cuenta[d] = { ...cuentaVacia(), ...(existentes?.[d] || {}) };
|
||||
ocup[d] = [...(bloques?.[d] || [])];
|
||||
});
|
||||
const orden = [...candidatos].sort((x, y) => (y.pct || 0) - (x.pct || 0) || (y.valor || 0) - (x.valor || 0));
|
||||
const items = [];
|
||||
for (const c of orden) {
|
||||
const lugar = colocar({ tipo, dias, cuenta, ocup, hoy, ahoraMin, urgente: (c.pct || 0) >= 80 });
|
||||
items.push({
|
||||
key: c.id,
|
||||
oppId: c.id,
|
||||
nombre: c.nombre,
|
||||
cliente: c.cliente,
|
||||
valor: c.valor,
|
||||
pct: c.pct,
|
||||
esRenovacion: !!c.esRenovacion,
|
||||
tipoCodigo: c.tipoCodigo ?? null,
|
||||
tipo,
|
||||
objetivo: c.objetivoSugerido || "",
|
||||
dia: lugar?.dia || null,
|
||||
hora: lugar?.hora || null,
|
||||
sinCupo: !lugar,
|
||||
incluir: !!lugar,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Las de forecast 80/90 % (`urgente`) van al día más temprano con cupo; el resto se reparte por carga
|
||||
// (el día con menos actividades primero) para que la semana quede pareja.
|
||||
function colocar({ tipo, dias, cuenta, ocup, hoy, ahoraMin, urgente }) {
|
||||
const tope = AGENDADOR.topes[tipo];
|
||||
const candidatos = dias
|
||||
.filter((d) => cuenta[d][tipo] < tope)
|
||||
.sort((a, b) => (urgente ? 0 : total(cuenta[a]) - total(cuenta[b])) || a.localeCompare(b));
|
||||
for (const d of candidatos) {
|
||||
if (tipo === "Tarea") {
|
||||
if (d === hoy && ahoraMin != null && AGENDADOR.horaTarea <= ahoraMin) continue;
|
||||
cuenta[d].Tarea++;
|
||||
return { dia: d, hora: minAHora(AGENDADOR.horaTarea) };
|
||||
}
|
||||
const dur = AGENDADOR.duracion[tipo];
|
||||
for (const s of horasDe(tipo)) {
|
||||
if (d === hoy && ahoraMin != null && s < ahoraMin + 30) continue;
|
||||
if (!libre(ocup[d], s, dur)) continue;
|
||||
ocup[d].push([s, s + dur]);
|
||||
cuenta[d][tipo]++;
|
||||
return { dia: d, hora: minAHora(s) };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Valida lo que se va a crear (items ya filtrados a los marcados). Devuelve los problemas por fila y
|
||||
// el conteo por día. La pantalla lo usa para avisar; el servidor lo vuelve a correr y NO crea nada si
|
||||
// hay algún problema.
|
||||
export function validar({ items, dias, existentes, bloques, hoy, ahoraMin }) {
|
||||
const porItem = {};
|
||||
const marca = (k, m) => (porItem[k] ||= []).push(m);
|
||||
const cuenta = {};
|
||||
const ocup = {};
|
||||
const dia = (d) => {
|
||||
cuenta[d] ||= { ...cuentaVacia(), ...(existentes?.[d] || {}) };
|
||||
ocup[d] ||= [...(bloques?.[d] || [])];
|
||||
};
|
||||
for (const it of items) {
|
||||
if (!TIPOS_AGENDADOR.includes(it.tipo)) { marca(it.key, "Tipo no válido."); continue; }
|
||||
if (!it.objetivo) marca(it.key, "Elige un objetivo.");
|
||||
else if (!OBJETIVOS_AGENDADOR.includes(it.objetivo)) marca(it.key, "Objetivo no permitido.");
|
||||
if (!dias.includes(it.dia)) { marca(it.key, "Elige un día hábil de la semana (desde hoy)."); continue; }
|
||||
dia(it.dia);
|
||||
cuenta[it.dia][it.tipo]++;
|
||||
if (cuenta[it.dia][it.tipo] > AGENDADOR.topes[it.tipo]) {
|
||||
marca(it.key, `Supera el máximo de ${AGENDADOR.topes[it.tipo]} ${it.tipo === "Tarea" ? "tareas" : it.tipo === "Cita" ? "visitas" : "llamadas"} por día.`);
|
||||
}
|
||||
if (it.tipo === "Tarea") continue;
|
||||
const s = horaAMin(it.hora);
|
||||
if (s == null || !horasDe(it.tipo).includes(s)) { marca(it.key, "Elige una hora dentro del horario (9:00–12:00 y 14:00–16:00)."); continue; }
|
||||
if (it.dia === hoy && ahoraMin != null && s < ahoraMin) marca(it.key, "Esa hora ya pasó.");
|
||||
const dur = AGENDADOR.duracion[it.tipo];
|
||||
if (!libre(ocup[it.dia], s, dur)) marca(it.key, "Se encima con otra actividad.");
|
||||
ocup[it.dia].push([s, s + dur]);
|
||||
}
|
||||
return { porItem, porDia: cuenta, ok: Object.keys(porItem).length === 0 };
|
||||
}
|
||||
|
||||
// Asunto y descripción de lo que se crea en Dynamics.
|
||||
export function asuntoDe(it) {
|
||||
const quien = (it.cliente || it.nombre || "").slice(0, 80);
|
||||
const base = `${it.objetivo}${quien ? `: ${quien}` : ""}`;
|
||||
return it.tipo === "Cita" ? `Visita – ${base}` : base;
|
||||
}
|
||||
export function descripcionDe(it, creadoPor) {
|
||||
const nota =
|
||||
it.tipo === "Cita"
|
||||
? " Completar en el CRM el lugar, los participantes y demás datos de la cita."
|
||||
: "";
|
||||
return `Creada por el agendador de la semana (${creadoPor}).${nota}`;
|
||||
}
|
||||
|
||||
// «Actividad para» (picklist de las actividades): Venta - Cliente Nuevo (100000000) → Cliente Nuevo
|
||||
// (100000001); el resto → Cliente Activo (100000000).
|
||||
export const actividadParaDe = (tipoCodigo) => (tipoCodigo === 100000000 ? 100000001 : 100000000);
|
||||
56
app/lib/agendadorLotes.js
Normal file
56
app/lib/agendadorLotes.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import db from "./db";
|
||||
|
||||
// Registro de cada tanda de actividades que crea el agendador: quién las creó, para quién y los ids
|
||||
// que quedaron en Dynamics. Sirve para (1) «Deshacer» una tanda (cancelando lo que siga abierto) y
|
||||
// (2) auditar. Se crea aquí (IF NOT EXISTS), igual que plan_cerrado: db.js se evalúa una sola vez por
|
||||
// proceso y una tabla agregada allí no existiría hasta reiniciar el servidor.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS agendador_lote (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
creado_por TEXT NOT NULL,
|
||||
creado_en TEXT NOT NULL,
|
||||
owner_id TEXT NOT NULL,
|
||||
owner_email TEXT NOT NULL,
|
||||
owner_name TEXT NOT NULL,
|
||||
desde TEXT NOT NULL,
|
||||
hasta TEXT NOT NULL,
|
||||
items TEXT NOT NULL,
|
||||
deshecho_en TEXT,
|
||||
deshecho_por TEXT,
|
||||
resumen_deshacer TEXT
|
||||
);
|
||||
`);
|
||||
|
||||
export function guardarLote({ creadoPor, ownerId, ownerEmail, ownerName, desde, hasta, items }) {
|
||||
const info = db
|
||||
.prepare(
|
||||
`INSERT INTO agendador_lote (creado_por, creado_en, owner_id, owner_email, owner_name, desde, hasta, items)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(creadoPor, new Date().toISOString(), ownerId, ownerEmail, ownerName, desde, hasta, JSON.stringify(items));
|
||||
return Number(info.lastInsertRowid);
|
||||
}
|
||||
|
||||
const fila = (r) => ({ ...r, items: JSON.parse(r.items) });
|
||||
|
||||
export function getLote(id) {
|
||||
const r = db.prepare("SELECT * FROM agendador_lote WHERE id = ?").get(id);
|
||||
return r ? fila(r) : null;
|
||||
}
|
||||
|
||||
// Tandas de un ejecutivo en una semana (las más recientes primero).
|
||||
export function getLotesSemana(ownerId, desde, hasta) {
|
||||
return db
|
||||
.prepare("SELECT * FROM agendador_lote WHERE owner_id = ? AND desde = ? AND hasta = ? ORDER BY id DESC LIMIT 20")
|
||||
.all(ownerId, desde, hasta)
|
||||
.map(fila);
|
||||
}
|
||||
|
||||
export function marcarDeshecho(id, por, resumen) {
|
||||
db.prepare("UPDATE agendador_lote SET deshecho_en = ?, deshecho_por = ?, resumen_deshacer = ? WHERE id = ?").run(
|
||||
new Date().toISOString(),
|
||||
por,
|
||||
JSON.stringify(resumen),
|
||||
id
|
||||
);
|
||||
}
|
||||
95
app/lib/agendadorServer.js
Normal file
95
app/lib/agendadorServer.js
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
// Agendador — acceso a Dynamics (solo servidor). Todo se hace con el token del usuario conectado
|
||||
// (derechos del propio usuario) y SIN caché: se valida con datos de este momento, no de hace 4 min.
|
||||
import { dvFresh, dvWrite, odataString } from "./dataverse";
|
||||
import { ENTIDAD_TIPO, aUtc, minAHora, horaAMin, AGENDADOR, asuntoDe, descripcionDe, actividadParaDe } from "./agendador";
|
||||
|
||||
// statuscode «Cancelada» de cada tipo (PLAYBOOK §10; probado en Dynamics el 2026-10-27).
|
||||
const STATUS_CANCELADA = { Llamada: 3, Cita: 4, Tarea: 6 };
|
||||
const NAV = {
|
||||
Llamada: { referente: "regardingobjectid_opportunity_phonecall", objetivo: "alfa_ObjetivodeActividad_PhoneCall" },
|
||||
Cita: { referente: "regardingobjectid_opportunity_appointment", objetivo: "alfa_ObjetivodeActividad_Appointment" },
|
||||
Tarea: { referente: "regardingobjectid_opportunity_task", objetivo: "alfa_ObjetivodeActividad_Task" },
|
||||
};
|
||||
const estadoDe = (statecode) => (statecode === 1 ? "completada" : statecode === 2 ? "cancelada" : "abierta");
|
||||
|
||||
// nombre del objetivo → id, leído del catálogo de Dynamics (no se fijan GUID en el código).
|
||||
export async function objetivosPorNombre(token) {
|
||||
const d = await dvFresh("alfa_objetivosdeactividadeses?$select=alfa_objetivo,alfa_objetivosdeactividadesid&$top=100", token);
|
||||
const m = new Map();
|
||||
(d.value || []).forEach((r) => m.set(String(r.alfa_objetivo || "").trim(), r.alfa_objetivosdeactividadesid));
|
||||
return m;
|
||||
}
|
||||
|
||||
// Actividades NO canceladas del ejecutivo cuya fecha cae en [desde, hasta] (días de Nicaragua).
|
||||
export async function actividadesFrescas(token, ownerId, desde, hasta) {
|
||||
const x = aUtc(desde, "00:00");
|
||||
const y = aUtc(hasta, "23:59");
|
||||
const filtro = `_ownerid_value eq ${ownerId} and statecode ne 2 and ((scheduledstart ge ${x} and scheduledstart le ${y}) or (scheduledend ge ${x} and scheduledend le ${y}))`;
|
||||
const res = await Promise.all(
|
||||
Object.entries(ENTIDAD_TIPO).map(async ([tipo, ent]) => {
|
||||
const d = await dvFresh(
|
||||
`${ent}?$select=activityid,scheduledstart,scheduledend,statecode,_regardingobjectid_value&$filter=${encodeURIComponent(filtro)}&$top=500`,
|
||||
token
|
||||
);
|
||||
return (d.value || []).map((r) => ({
|
||||
id: r.activityid,
|
||||
tipo,
|
||||
estado: estadoDe(r.statecode),
|
||||
scheduledstart: r.scheduledstart || null,
|
||||
scheduledend: r.scheduledend || null,
|
||||
oppId: r._regardingobjectid_value || null,
|
||||
}));
|
||||
})
|
||||
);
|
||||
return res.flat();
|
||||
}
|
||||
|
||||
// Oportunidades (abiertas o no) por id, de a 25.
|
||||
export async function oportunidadesFrescas(token, ids) {
|
||||
const m = new Map();
|
||||
for (let i = 0; i < ids.length; i += 25) {
|
||||
const trozo = ids.slice(i, i + 25);
|
||||
const f = trozo.map((id) => `opportunityid eq ${odataString(id)}`).join(" or ");
|
||||
const d = await dvFresh(
|
||||
`opportunities?$select=opportunityid,name,statecode,alfa_typeopportunity,_ownerid_value&$filter=${encodeURIComponent(f)}`,
|
||||
token
|
||||
);
|
||||
(d.value || []).forEach((o) =>
|
||||
m.set(o.opportunityid, { id: o.opportunityid, nombre: o.name, abierta: o.statecode === 0, tipoCodigo: o.alfa_typeopportunity ?? null, ownerId: o._ownerid_value })
|
||||
);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
// Crea UNA actividad ligada a la oportunidad, con el propietario de la oportunidad. Devuelve su id.
|
||||
export async function crearActividad(token, it, opp, ownerId, objetivoId, creadoPor) {
|
||||
const nav = NAV[it.tipo];
|
||||
const body = {
|
||||
subject: asuntoDe(it),
|
||||
description: descripcionDe(it, creadoPor),
|
||||
alfa_actividadpara: actividadParaDe(opp.tipoCodigo),
|
||||
"ownerid@odata.bind": `/systemusers(${ownerId})`,
|
||||
[`${nav.referente}@odata.bind`]: `/opportunities(${it.oppId})`,
|
||||
[`${nav.objetivo}@odata.bind`]: `/alfa_objetivosdeactividadeses(${objetivoId})`,
|
||||
};
|
||||
if (it.tipo === "Tarea") {
|
||||
body.scheduledstart = aUtc(it.dia, minAHora(AGENDADOR.horaTarea));
|
||||
body.scheduledend = body.scheduledstart;
|
||||
} else {
|
||||
body.scheduledstart = aUtc(it.dia, it.hora);
|
||||
body.scheduledend = aUtc(it.dia, minAHora(horaAMin(it.hora) + AGENDADOR.duracion[it.tipo]));
|
||||
if (it.tipo === "Llamada") body.directioncode = true;
|
||||
}
|
||||
const r = await dvWrite("POST", `${ENTIDAD_TIPO[it.tipo]}?$select=activityid`, token, body);
|
||||
return r.activityid;
|
||||
}
|
||||
|
||||
// Cancela una actividad creada por el agendador SOLO si sigue abierta (si ya se completó o canceló, no
|
||||
// se toca). Devuelve "cancelada" | "ya cerrada".
|
||||
export async function cancelarActividad(token, tipo, id) {
|
||||
const ent = ENTIDAD_TIPO[tipo];
|
||||
const d = await dvFresh(`${ent}(${odataString(id)})?$select=statecode`, token);
|
||||
if (d.statecode === 1 || d.statecode === 2) return "ya cerrada";
|
||||
await dvWrite("PATCH", `${ent}(${odataString(id)})`, token, { statecode: 2, statuscode: STATUS_CANCELADA[tipo] });
|
||||
return "cancelada";
|
||||
}
|
||||
72
app/lib/auth.js
Normal file
72
app/lib/auth.js
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import NextAuth from "next-auth";
|
||||
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";
|
||||
|
||||
const DV = process.env.DATAVERSE_URL; // https://<org>.crm.dynamics.com
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
trustHost: true,
|
||||
providers: [
|
||||
MicrosoftEntraID({
|
||||
clientId: process.env.AZURE_CLIENT_ID,
|
||||
clientSecret: process.env.AZURE_CLIENT_SECRET,
|
||||
issuer: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`,
|
||||
authorization: {
|
||||
params: {
|
||||
scope: `openid profile email offline_access ${DV}/user_impersonation`,
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, account }) {
|
||||
if (account) {
|
||||
token.accessToken = account.access_token;
|
||||
token.refreshToken = account.refresh_token;
|
||||
token.expiresAt = account.expires_at;
|
||||
}
|
||||
if (token.expiresAt && Date.now() / 1000 > token.expiresAt - 300 && token.refreshToken) {
|
||||
try {
|
||||
const r = await fetch(
|
||||
`https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/oauth2/v2.0/token`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
client_id: process.env.AZURE_CLIENT_ID,
|
||||
client_secret: process.env.AZURE_CLIENT_SECRET,
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: token.refreshToken,
|
||||
scope: `openid profile email offline_access ${DV}/user_impersonation`,
|
||||
}),
|
||||
}
|
||||
);
|
||||
if (r.ok) {
|
||||
const d = await r.json();
|
||||
token.accessToken = d.access_token;
|
||||
token.expiresAt = Math.floor(Date.now() / 1000) + d.expires_in;
|
||||
if (d.refresh_token) token.refreshToken = d.refresh_token;
|
||||
} else {
|
||||
token.error = "RefreshFailed";
|
||||
}
|
||||
} catch {
|
||||
token.error = "RefreshFailed";
|
||||
}
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
session.accessToken = token.accessToken;
|
||||
session.error = token.error;
|
||||
const email = (session.user?.email || "").toLowerCase();
|
||||
session.email = email;
|
||||
session.isAdmin = (process.env.ADMIN_EMAILS || "")
|
||||
.toLowerCase()
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.includes(email);
|
||||
return session;
|
||||
},
|
||||
},
|
||||
session: { strategy: "jwt" },
|
||||
});
|
||||
38
app/lib/authz.js
Normal file
38
app/lib/authz.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { AGENDADOR } from "./agendador";
|
||||
|
||||
// requestedOwnerParam: emails separados por coma (multi-selección, ver components/OwnerControl.js).
|
||||
// scope.emails = [] significa "todos" — ni el admin ni ningún query filtran por propietario.
|
||||
//
|
||||
// opts.asistente: solo lo pasan Plan del Día y Plan de Actividades. La asistente de ventas
|
||||
// (AGENDADOR.asistentes) NO es administradora: ahí ve únicamente a los ejecutivos del piloto
|
||||
// (AGENDADOR.piloto); en el resto de páginas se comporta como cualquier usuario sin rol.
|
||||
export function ownerFilter(session, requestedOwnerParam, opts = {}) {
|
||||
if (!session?.email) throw new Error("NO_SESSION");
|
||||
|
||||
const pedidos = requestedOwnerParam
|
||||
? requestedOwnerParam.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
|
||||
: [];
|
||||
|
||||
// Admin: puede pedir uno o varios vendedores, o ninguno (= todos).
|
||||
if (session.isAdmin) return { emails: pedidos, locked: false };
|
||||
|
||||
if (opts.asistente && esAsistente(session.email)) {
|
||||
const permitidos = pedidos.filter((e) => AGENDADOR.piloto.includes(e));
|
||||
return { emails: permitidos.length ? permitidos : [...AGENDADOR.piloto], locked: false, asistente: true };
|
||||
}
|
||||
|
||||
// Vendedor: siempre su propio correo, ignorando lo que pida el cliente.
|
||||
return { emails: [session.email], locked: true };
|
||||
}
|
||||
|
||||
export function esAsistente(email) {
|
||||
return AGENDADOR.asistentes.includes(String(email || "").toLowerCase());
|
||||
}
|
||||
|
||||
// ¿Puede esta sesión agendar para `ownerEmail`? Solo ejecutivos del piloto; lo hace el administrador,
|
||||
// la asistente, o el propio ejecutivo.
|
||||
export function puedeAgendarPara(session, ownerEmail) {
|
||||
const o = String(ownerEmail || "").toLowerCase();
|
||||
if (!session?.email || !AGENDADOR.piloto.includes(o)) return false;
|
||||
return !!session.isAdmin || esAsistente(session.email) || session.email === o;
|
||||
}
|
||||
44
app/lib/constants.js
Normal file
44
app/lib/constants.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
export const DYN =
|
||||
"https://alfanumeric.crm.dynamics.com/main.aspx?appid=eb8b70d7-5a69-e911-a998-000d3a1a42fe&pagetype=entityrecord&etn=opportunity&id=";
|
||||
|
||||
// Registro de cualquier entidad en Dynamics (oportunidad, caso `incident`, cuenta `account`).
|
||||
export function registroUrl(etn, id) {
|
||||
return DYN.replace("etn=opportunity", `etn=${etn}`) + id;
|
||||
}
|
||||
|
||||
// Formulario NUEVO de Tarea (`task`), Cita (`appointment`) o Llamada de teléfono (`phonecall`) ya
|
||||
// ligado a una oportunidad ("Referente a" prellenado) — botones de «Agendar» de Plan del Día. Los
|
||||
// parámetros viajan en `extraqs` (formato estándar de Dynamics para prellenar un formulario nuevo);
|
||||
// no crea nada hasta que el usuario guarda.
|
||||
// ⚠ El tipo del «Referente a» va en `regardingobjectidtype` (nombre de la entidad). Con
|
||||
// `regardingobjecttypecode=opportunity` el formulario SE VE bien pero al guardar falla con
|
||||
// 0x80040217 («el registro no está disponible»); con el código numérico (=3) tampoco funciona.
|
||||
// Probado con guardado real por Marco el 2026-10-27.
|
||||
export const TIPOS_NUEVA_ACTIVIDAD = [
|
||||
{ etn: "task", label: "Tarea", ayuda: "Nueva tarea ligada a esta oportunidad" },
|
||||
{ etn: "appointment", label: "Cita", ayuda: "Nueva cita ligada a esta oportunidad" },
|
||||
{ etn: "phonecall", label: "Llamada", ayuda: "Nueva llamada de teléfono ligada a esta oportunidad (también para registrar seguimientos por WhatsApp)" },
|
||||
];
|
||||
export function nuevaActividadUrl(opp, etn = "phonecall") {
|
||||
const extra =
|
||||
`regardingobjectid=${opp.id}®ardingobjectidname=${encodeURIComponent(opp.nombre || "")}` +
|
||||
`®ardingobjectidtype=opportunity`;
|
||||
return DYN.replace("etn=opportunity", `etn=${etn}`).replace(/&id=$/, "") + "&extraqs=" + encodeURIComponent(extra);
|
||||
}
|
||||
|
||||
const ACT_ETN = { Tarea: "task", Cita: "appointment", Llamada: "phonecall" };
|
||||
export function actividadUrl(a) {
|
||||
return DYN.replace("etn=opportunity", `etn=${ACT_ETN[a.tipo] || "phonecall"}`) + a.id;
|
||||
}
|
||||
|
||||
export const ACT_COLOR = {
|
||||
Activa: "#3f7d5c",
|
||||
Tibia: "#C98A1B",
|
||||
Fría: "#d1642a",
|
||||
Congelada: "#B23A2E",
|
||||
"Sin dato": "#9db4c9",
|
||||
};
|
||||
|
||||
export const money = (n) => "$" + Math.round(n || 0).toLocaleString("en-US");
|
||||
export const money2 = (n) =>
|
||||
"$" + (n || 0).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
98
app/lib/dataverse.js
Normal file
98
app/lib/dataverse.js
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
const BASE = `${process.env.DATAVERSE_URL}/api/data/v9.2`;
|
||||
const MAX_RETRIES = 3;
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// Reintenta 429 (throttling de Dataverse) respetando Retry-After — ver migration.md §8.
|
||||
export async function dv(path, accessToken, attempt = 0) {
|
||||
const r = await fetch(`${BASE}/${path}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: "application/json",
|
||||
"OData-MaxVersion": "4.0",
|
||||
"OData-Version": "4.0",
|
||||
// FormattedValue: etiqueta legible de option sets. lookuplogicalname: qué entidad es un lookup
|
||||
// polimórfico (ej. "Referente a" de una actividad puede ser cuenta U oportunidad) — sin esto
|
||||
// no hay forma de saber a qué tabla apunta un _regardingobjectid_value.
|
||||
Prefer: 'odata.include-annotations="OData.Community.Display.V1.FormattedValue,Microsoft.Dynamics.CRM.lookuplogicalname"',
|
||||
},
|
||||
// Caché de 4 min en vez de no-store — decisión revisada: la versión 100% en vivo (sin caché)
|
||||
// tardaba 2-4s por página. Subido de 90s a 240s (2026-09-22, a pedido de Marco tras seguir
|
||||
// viendo 4s): más frecuencia de reuso de caché, a cambio de hasta 4 min de atraso en vez de
|
||||
// 1.5 — razonable para un informe que se consulta, no un panel en tiempo real. El alcance
|
||||
// (owner) ya viaja en la URL vía $filter, así que cachear por URL no filtra datos entre
|
||||
// usuarios con distinto alcance — la Capa 2 de autorización (ownerFilter) sigue siendo la que
|
||||
// decide qué URL se pide, no el token. Ver migration.md §8, "plan B" ya documentado ahí.
|
||||
next: { revalidate: 240 },
|
||||
});
|
||||
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
|
||||
if (r.status === 429 && attempt < MAX_RETRIES) {
|
||||
const retryAfter = Number(r.headers.get("Retry-After")) || 2 ** attempt;
|
||||
await sleep(retryAfter * 1000);
|
||||
return dv(path, accessToken, attempt + 1);
|
||||
}
|
||||
if (!r.ok) throw new Error(`DATAVERSE_${r.status}: ${(await r.text()).slice(0, 300)}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
// Lectura SIN caché (cache: "no-store"): para validar justo antes de escribir — el `dv()` de arriba
|
||||
// puede traer datos de hasta 4 min atrás.
|
||||
export async function dvFresh(path, accessToken) {
|
||||
const r = await fetch(`${BASE}/${path}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: "application/json",
|
||||
"OData-MaxVersion": "4.0",
|
||||
"OData-Version": "4.0",
|
||||
Prefer: 'odata.include-annotations="OData.Community.Display.V1.FormattedValue,Microsoft.Dynamics.CRM.lookuplogicalname"',
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
|
||||
if (!r.ok) throw new Error(`DATAVERSE_${r.status}: ${(await r.text()).slice(0, 300)}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
// Escritura (POST crea, PATCH actualiza) con los derechos del usuario conectado (token delegado).
|
||||
// Devuelve el JSON creado (POST, `return=representation`) o null (PATCH, 204). Solo la usa el
|
||||
// agendador (lib/agendadorServer.js).
|
||||
export async function dvWrite(method, path, accessToken, body) {
|
||||
const r = await fetch(`${BASE}/${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"OData-MaxVersion": "4.0",
|
||||
"OData-Version": "4.0",
|
||||
...(method === "POST" ? { Prefer: "return=representation" } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
|
||||
if (!r.ok) {
|
||||
let msg = "";
|
||||
try { msg = (await r.json())?.error?.message || ""; } catch { /* sin cuerpo */ }
|
||||
throw new Error(`DATAVERSE_${r.status}: ${msg.slice(0, 300)}`);
|
||||
}
|
||||
return r.status === 204 ? null : r.json();
|
||||
}
|
||||
|
||||
// Etiqueta legible de un option set, entregada por el header Prefer de arriba.
|
||||
export function fv(o, key) {
|
||||
return o[`${key}@OData.Community.Display.V1.FormattedValue`] || null;
|
||||
}
|
||||
|
||||
// A qué entidad apunta un lookup polimórfico — key con el mismo formato que fv(), ej.
|
||||
// lookupType(o, "_regardingobjectid_value").
|
||||
export function lookupType(o, key) {
|
||||
return o[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] || null;
|
||||
}
|
||||
|
||||
export function odataString(s) {
|
||||
return String(s).replace(/'/g, "''");
|
||||
}
|
||||
|
||||
35
app/lib/db.js
Normal file
35
app/lib/db.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import Database from "better-sqlite3";
|
||||
import path from "node:path";
|
||||
import fs from "node:fs";
|
||||
|
||||
// process.cwd() es /app dentro del contenedor (WORKDIR /app en el Dockerfile),
|
||||
// donde Coolify monta el volumen persistente en /app/data.
|
||||
function createDb() {
|
||||
const dir = path.join(process.cwd(), "data");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const db = new Database(path.join(dir, "informe.db"));
|
||||
db.pragma("journal_mode = WAL");
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS metas (
|
||||
email TEXT PRIMARY KEY,
|
||||
monto REAL NOT NULL,
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
clave TEXT PRIMARY KEY,
|
||||
valor TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS geo_override (
|
||||
opportunity_id TEXT PRIMARY KEY,
|
||||
lat REAL,
|
||||
lon REAL,
|
||||
zona TEXT,
|
||||
depto TEXT
|
||||
);
|
||||
`);
|
||||
return db;
|
||||
}
|
||||
|
||||
const g = globalThis;
|
||||
const db = g.__informeDb ?? (g.__informeDb = createDb());
|
||||
export default db;
|
||||
313
app/lib/derive.js
Normal file
313
app/lib/derive.js
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
// Cálculos portados de herramientas/sync_pipe.js (ETL estático) — misma lógica, servidor en vivo.
|
||||
|
||||
export const CARTERA = ["Up-Selling", "Cross-Selling", "Plan de Cuenta"];
|
||||
|
||||
export const PESO_PLAN = {
|
||||
"Plan A - En firma": 0.9,
|
||||
"Plan B - En Negociación": 0.6,
|
||||
"Plan C - En seguimiento": 0.3,
|
||||
"Plan D - Recalificar": 0.15,
|
||||
"Sin plan de cierre": 0.1,
|
||||
};
|
||||
export const PLAN_ORDER = Object.keys(PESO_PLAN);
|
||||
|
||||
// Prioridad: campo de Dynamics (`prioritycode`, etiqueta en `o.prioridad`); lo registra el ejecutivo,
|
||||
// no se calcula. Colores por etiqueta; cualquier valor que no esté aquí cae en «Sin prioridad».
|
||||
export const PRIORIDAD_COLOR = {
|
||||
Alta: { fg: "#8f2a20", bg: "#fbe0dc" },
|
||||
Normal: { fg: "#2f6590", bg: "#e3eef8" },
|
||||
Baja: { fg: "#4b6b4f", bg: "#e4f0e5" },
|
||||
"Sin prioridad": { fg: "#5b6b7a", bg: "#eceff2" },
|
||||
};
|
||||
export const esPrioridadAlta = (o) => /^alta/i.test(o.prioridad || "");
|
||||
|
||||
export function cierreVencido(o) {
|
||||
return !!o.close && o.close < new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function nomCorto(n) {
|
||||
const p = (n || "").split(" ");
|
||||
return p.length > 2 ? `${p[0]} ${p[p.length - 2]}` : n || "";
|
||||
}
|
||||
|
||||
// Los 4 tipos que cuentan para cumplimiento de meta (ver CLAUDE.md — se excluyen renovaciones y SAC).
|
||||
export const TIPOS_META = ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling", "Plan de Cuenta"];
|
||||
|
||||
// Ejecutivos de venta reales (ver CLAUDE.md). Gabriela Sánchez y Ashley Bermúdez aparecen
|
||||
// en los datos de Dynamics pero no son ejecutivas de venta — se excluyen del selector.
|
||||
export const EJECUTIVOS_VENTA = [
|
||||
"Mirna Obando Morras",
|
||||
"Maria Auxiliadora Marenco Abea",
|
||||
"Denis Urroz Manzanares",
|
||||
"Daybellys Perez Sequeira",
|
||||
"Martha Somarriba Sirias",
|
||||
];
|
||||
|
||||
// Selector de propietario en páginas de Ventas (Resumen, Ganadas, Perdemos, Tendencia): además de
|
||||
// los ejecutivos de venta oficiales, Ashley Bermúdez y Gabriela Sánchez tienen permiso de vender a
|
||||
// ciertos clientes y sus oportunidades ganadas/perdidas de tipo Venta sí cuentan (corregido
|
||||
// 2026-09-28 — ver sesion.md). El cumplimiento de meta INDIVIDUAL (tabla por ejecutivo) sigue
|
||||
// usando solo EJECUTIVOS_VENTA: son las únicas con meta asignada en metas.json.
|
||||
export const PROPIETARIOS_VENTA = [...EJECUTIVOS_VENTA, "Ashley Bermudez Valverde", "Gabriela Sánchez Villareyna"];
|
||||
|
||||
// Renovaciones y cohorte NO se filtran a rol 'ventas' — SAC renueva tanto como Ventas (ver
|
||||
// CLAUDE.md). Alcance verificado contra Dynamics: ventas+sac con datos reales en wonRen/pipeRen.
|
||||
export const EJECUTIVOS_RENOV = [
|
||||
"Ashley Bermudez Valverde",
|
||||
"Daybellys Perez Sequeira",
|
||||
"Denis Urroz Manzanares",
|
||||
"Gabriela Sánchez Villareyna",
|
||||
"José Centeno Silva",
|
||||
"Maria Auxiliadora Marenco Abea",
|
||||
"Martha Somarriba Sirias",
|
||||
"Mirna Obando Morras",
|
||||
"Ricardo Silva Ramírez",
|
||||
];
|
||||
|
||||
export function segmentoDe(tipo) {
|
||||
return CARTERA.includes(tipo) ? "Cartera Activa" : "Clientes Nuevos";
|
||||
}
|
||||
|
||||
// El competidor viene con mayúsculas inconsistentes desde el CRM ('Tigo' y 'TIGO' son el mismo).
|
||||
// 'Se Desconoce' y el vacío NO se mezclan: "no sé contra quién compito" y "no lo llené" son cosas
|
||||
// distintas (ver herramientas/sync_pipe.js del sitio HTML, misma tabla de canónicos).
|
||||
const COMP_CANON = {
|
||||
tigo: "Tigo", claro: "Claro", ideay: "Ideay", ufinet: "UFINET", enatrel: "Enatrel",
|
||||
"ibw comunicaciones": "IBW Comunicaciones", starlink: "Starlink", casavision: "CasaVision",
|
||||
alliance: "Alliance", ninguno: "Ninguno", otro: "Otro", "se desconoce": "Se desconoce",
|
||||
};
|
||||
export function normComp(c) {
|
||||
if (!c) return "Sin registrar";
|
||||
return COMP_CANON[c.trim().toLowerCase()] || c.trim();
|
||||
}
|
||||
|
||||
export const CLASIF_ORDER = ["Hirviendo", "Caliente", "Cálida", "Tibia", "Fría", "Sin clasificar"];
|
||||
export const CLASIF_COLOR = {
|
||||
Hirviendo: "#B23A2E", Caliente: "#d1642a", "Cálida": "#C98A1B", Tibia: "#5c8fb8",
|
||||
"Fría": "#7f96a8", "Sin clasificar": "#c2ccd6",
|
||||
};
|
||||
const CALIDAD_DE = { Hirviendo: "Alta", Caliente: "Alta", "Cálida": "Media", Tibia: "Baja", "Fría": "Baja" };
|
||||
export const CALIDAD_ORDER = ["Alta", "Media", "Baja", "Sin clasificar"];
|
||||
export const CALIDAD_COLOR = { Alta: "#B23A2E", Media: "#C98A1B", Baja: "#7f96a8", "Sin clasificar": "#c2ccd6" };
|
||||
export function calidadDe(clasif) {
|
||||
return CALIDAD_DE[clasif] || "Sin clasificar";
|
||||
}
|
||||
export function hayClasif(arr) {
|
||||
return arr.some((o) => o.clasif && o.clasif !== "Sin clasificar");
|
||||
}
|
||||
|
||||
// Catálogo cerrado 2026-08-17 (21 objetivos activos, 7 etapas) — ver
|
||||
// Proyectos/Mejoras Dynamics CRM/Actividades en CRM/estado-proyecto-agosto2026.md, replicado tal
|
||||
// cual desde herramientas/build_actividades.js del sitio HTML (no inventar valores nuevos acá).
|
||||
const ETAPAS = [
|
||||
{ etapa: "1. Prospección y calificación", objetivos: ["Prospección", "Calificar Oportunidad"] },
|
||||
{ etapa: "2. Diagnóstico y cierre", objetivos: ["Diagnosticar Necesidades", "Presentación de Servicio", "Presentar Oferta", "Negociación", "Firma Contrato-Adendum"] },
|
||||
{ etapa: "3. Renovación", objetivos: ["Renovación"] },
|
||||
{ etapa: "4. Gestión de cuentas (Mapa de Jugadores)", objetivos: ["Identificar Campeón", "Fortalecer Campeón", "Gestionar Anticampeón"] },
|
||||
{ etapa: "5. Retención y riesgo", objetivos: ["Control de daños", "Retención", "Postventa/Cobro", "Encuestar"] },
|
||||
{ etapa: "6. Actividades específicas de servicio", objetivos: ["Prospectar Vecinos FO", "Reunión Técnica", "Recopilación Proyecto SW"] },
|
||||
{ etapa: "7. Administrativo", objetivos: ["Planificación", "Gestión Admin.", "Otro"] },
|
||||
];
|
||||
export const ETAPA_ORDER = ETAPAS.map((e) => e.etapa);
|
||||
export const OBJETIVO_A_ETAPA = {};
|
||||
ETAPAS.forEach((e) => e.objetivos.forEach((o) => { OBJETIVO_A_ETAPA[o] = e.etapa; }));
|
||||
|
||||
// Campo que ancla el horizonte y el cálculo de Vencida — Cita es un bloque de calendario (importa
|
||||
// CUÁNDO EMPIEZA), Tarea/Llamada son ítems de trabajo con fecha de compromiso (importa PARA CUÁNDO
|
||||
// debían estar listas). Replicado de assets/js/pages/actividades.js del sitio HTML.
|
||||
export function actAncla(a) {
|
||||
return a.tipo === "Cita" ? a.scheduledstart : a.scheduledend || a.scheduledstart;
|
||||
}
|
||||
export function actEstadoFinal(a) {
|
||||
if (a.estado === "completada") return "Completada";
|
||||
if (a.estado === "cancelada") return "Cancelada";
|
||||
const f = actAncla(a);
|
||||
if (!f) return "Pendiente";
|
||||
const anclaDia = new Date(f);
|
||||
anclaDia.setHours(0, 0, 0, 0);
|
||||
const hoy = new Date();
|
||||
hoy.setHours(0, 0, 0, 0);
|
||||
return anclaDia < hoy ? "Vencida" : "Pendiente";
|
||||
}
|
||||
|
||||
// Igual que agg(), pero ordena por un orden declarado (orden) en vez de por frecuencia — para ejes
|
||||
// como Plan de Cierre o Fase, donde el orden natural del negocio importa más que el conteo.
|
||||
export function aggOrd(arr, key, orden, valfn) {
|
||||
return agg(arr, key, valfn).sort((a, b) => {
|
||||
const ia = orden.indexOf(a.k), ib = orden.indexOf(b.k);
|
||||
return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib);
|
||||
});
|
||||
}
|
||||
|
||||
// Dimensiones conmutables de la matriz de ejecutivos (ExecMatrix) — puerto de MTZ_DIMS
|
||||
// (assets/js/tables.js del sitio HTML). Cada una: `k` (campo de la fila), `lbl` (pestaña),
|
||||
// `orden` (comparador para las columnas) y `corto` (etiqueta corta de columna).
|
||||
// Nota: "Fase" no tiene un orden canónico portado todavía (el HTML normaliza 3 vocabularios de
|
||||
// proceso distintos con FASE_MAP/FASE_ORDER, ver sesion.md — no replicado en Next.js aún), así que
|
||||
// queda ordenada por frecuencia en vez de por el embudo real.
|
||||
// Fases del embudo — la misma escalera con nombres distintos según el flujo de proceso de Dynamics
|
||||
// (ver CLAUDE.md de Analítica de CRM). Decisión de Marco (2026-10-05): Oferta, Cotización y Proponer
|
||||
// se unifican en "Proponer"; Desarrollar/Desarrollo en "Desarrollo". Calificar y Cerrar Oferta no
|
||||
// están en el mapeo final y quedan con su nombre original. Ganada/Perdida cierran el embudo.
|
||||
export const FASE_MAP = {
|
||||
Crear: "Crear",
|
||||
Desarrollar: "Desarrollo",
|
||||
Desarrollo: "Desarrollo",
|
||||
Oferta: "Proponer",
|
||||
"Cotización": "Proponer",
|
||||
Proponer: "Proponer",
|
||||
"Negociación": "Negociación",
|
||||
};
|
||||
export const FASE_ORDER = ["Crear", "Desarrollo", "Proponer", "Negociación", "Ganada", "Perdida"];
|
||||
export const normalizarFase = (f) => (f ? FASE_MAP[f.trim()] || f.trim() : f);
|
||||
const ordenFase = (a, b) => {
|
||||
const ia = FASE_ORDER.indexOf(a), ib = FASE_ORDER.indexOf(b);
|
||||
return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib);
|
||||
};
|
||||
|
||||
export const MTZ_DIMS = [
|
||||
{ k: "plan", lbl: "Plan de Cierre", orden: (a, b) => PLAN_ORDER.indexOf(a) - PLAN_ORDER.indexOf(b), corto: (s) => s.replace("Plan ", "").replace(" - ", " ") },
|
||||
{ k: "prev", lbl: "Categoría Previsión", orden: (a, b) => (parseInt(a, 10) || 0) - (parseInt(b, 10) || 0), corto: (s) => s.replace(/^\d+%\s*/, "") },
|
||||
{ k: "actividad", lbl: "Actividad", orden: (a, b) => ["Activa", "Tibia", "Fría", "Congelada"].indexOf(a) - ["Activa", "Tibia", "Fría", "Congelada"].indexOf(b), corto: (s) => s },
|
||||
{ k: "clasif", lbl: "Temperatura", orden: (a, b) => CLASIF_ORDER.indexOf(a) - CLASIF_ORDER.indexOf(b), corto: (s) => s },
|
||||
{ k: "faseActual", lbl: "Fase", orden: ordenFase, corto: (s) => s },
|
||||
];
|
||||
|
||||
// Agrupa arr por o[key], contando y sumando valfn(o). Ordena por conteo descendente.
|
||||
export function agg(arr, key, valfn) {
|
||||
const m = new Map();
|
||||
arr.forEach((o) => {
|
||||
const k = o[key] || "(sin dato)";
|
||||
if (!m.has(k)) m.set(k, { n: 0, v: 0 });
|
||||
const e = m.get(k);
|
||||
e.n++;
|
||||
e.v += valfn ? valfn(o) : 0;
|
||||
});
|
||||
return [...m.entries()].map(([k, x]) => ({ k, ...x })).sort((a, b) => b.n - a.n);
|
||||
}
|
||||
|
||||
// Cruce Actividades × Tubería/Previsión — puerto de decorarActividadVentana()/actividadesEnVentana()
|
||||
// (App Informe/assets/js/utils.js). `actividades` viene de getActividades() (queries.js);
|
||||
// `ini`/`fin` acotan la ventana de fechas (abierta para Tubería, el mes/atrasadas para Previsión).
|
||||
// A diferencia del HTML no muta in-place — devuelve un array nuevo (más idiomático en Server
|
||||
// Components).
|
||||
//
|
||||
// «Agendada» = actividad PENDIENTE (abierta; no completada ni cancelada) cuya fecha cae entre HOY y
|
||||
// `fin` (y no antes de `ini`). La columna Agenda muestra la más próxima. Antes contaba también las
|
||||
// ya completadas y las de días pasados del mes, y mostraba la más antigua: una oportunidad con una
|
||||
// llamada abierta para hoy aparecía con «05/10» (una llamada completada hace semanas) — corregido
|
||||
// 2026-10-27. La fecha es la de `actAncla()` (Cita = inicio; Tarea/Llamada = vencimiento), la misma
|
||||
// que usan Plan del Día y Agenda.
|
||||
function hoyManagua() {
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone: "America/Managua" }).format(new Date());
|
||||
}
|
||||
export function decorarActividadVentana(arr, actividades, ini, fin) {
|
||||
const m = new Map();
|
||||
const desde = ini > hoyManagua() ? ini : hoyManagua();
|
||||
(actividades || []).forEach((a) => {
|
||||
if (a.estado !== "abierta" || !a.referente || a.referente.tipo !== "opportunity") return;
|
||||
const anc = actAncla(a);
|
||||
if (!anc) return;
|
||||
const f = String(anc).slice(0, 10);
|
||||
if (f < desde || f > fin) return;
|
||||
if (!m.has(a.referente.id) || f < m.get(a.referente.id)) m.set(a.referente.id, f);
|
||||
});
|
||||
return arr.map((o) => {
|
||||
const f = m.get(o.id) || null;
|
||||
return { ...o, actFecha: f, actAgendada: f ? "Con actividad agendada" : "Sin actividad agendada" };
|
||||
});
|
||||
}
|
||||
export const ACTAGENDADA_ORDEN = ["Con actividad agendada", "Sin actividad agendada"];
|
||||
|
||||
// Agrupa ganadas+perdidas por una dimensión y adjunta el motivo de pérdida más frecuente de cada
|
||||
// categoría — puerto de catsWonLost() (App Informe/assets/js/tables.js), para comparePanelMotivo.
|
||||
// wonVal/lostVal: por defecto MRR realmente cobrado (won.actual) vs. estimado perdido (lost.est) —
|
||||
// mismo criterio que "Ventas Ganadas"/"Por qué Perdemos".
|
||||
export function catsWonLost(wonArr, lostArr, key, wonVal = (o) => o.actual || 0, lostVal = (o) => o.est || 0) {
|
||||
const keys = [...new Set([...wonArr.map((o) => o[key]), ...lostArr.map((o) => o[key])].filter(Boolean))];
|
||||
return keys
|
||||
.map((k) => {
|
||||
const g = wonArr.filter((o) => o[key] === k);
|
||||
const l = lostArr.filter((o) => o[key] === k);
|
||||
// Excluye "Descartada sin motivo (depuración)" del ranking — es higiene de datos, no una
|
||||
// razón de negocio real que explique la pérdida (ver CLAUDE.md).
|
||||
const mm = {};
|
||||
l.forEach((o) => {
|
||||
if (o.motivo && o.motivo !== "Descartada sin motivo (depuración)") mm[o.motivo] = (mm[o.motivo] || 0) + 1;
|
||||
});
|
||||
const top = Object.entries(mm).sort((a, b) => b[1] - a[1])[0];
|
||||
const depu = l.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||
return {
|
||||
k,
|
||||
ganaN: g.length,
|
||||
ganaV: g.reduce((s, o) => s + wonVal(o), 0),
|
||||
pierdeN: l.length,
|
||||
pierdeV: l.reduce((s, o) => s + lostVal(o), 0),
|
||||
topMotivo: top ? top[0] : null,
|
||||
topMotivoN: top ? top[1] : 0,
|
||||
depu,
|
||||
};
|
||||
})
|
||||
.filter((c) => c.ganaN || c.pierdeN)
|
||||
.sort((a, b) => b.ganaN + b.pierdeN - (a.ganaN + a.pierdeN));
|
||||
}
|
||||
|
||||
// Velocidad de movimiento: promedio/mediana/peor caso por fase — puerto de pipeVelFor()
|
||||
// (App Informe/assets/js/tables.js). `stageDurations` viene de getStageDurations() (queries.js),
|
||||
// ya con "Fase: " recortado y el nombre normalizado con FASE_MAP. Ordena de más lenta a más
|
||||
// rápida; una fase fuera del mapeo (Calificar, Cerrar Oferta) se muestra con su nombre original
|
||||
// para no esconder en silencio sus duraciones.
|
||||
export function pipeVelFor(arr, stageDurations) {
|
||||
const ids = new Set(arr.map((o) => o.id));
|
||||
const byId = new Map(arr.map((o) => [o.id, o]));
|
||||
const relevant = stageDurations.filter((r) => ids.has(r.oppId));
|
||||
const fases = [...new Set(relevant.map((r) => r.fase))];
|
||||
return fases
|
||||
.map((f) => {
|
||||
const regs = relevant.filter((r) => r.fase === f);
|
||||
const n = regs.length;
|
||||
const durs = regs.map((r) => r.dur).sort((a, b) => a - b);
|
||||
const prom = durs.reduce((a, b) => a + b, 0) / n;
|
||||
const mediana = n % 2 ? durs[(n - 1) / 2] : (durs[n / 2 - 1] + durs[n / 2]) / 2;
|
||||
const peorReg = regs.reduce((mx, r) => (r.dur > mx.dur ? r : mx), regs[0]);
|
||||
const peorOpp = byId.get(peorReg.oppId);
|
||||
return { fase: f, prom: +prom.toFixed(2), n, mediana, peor: peorOpp ? { dur: peorReg.dur, name: peorOpp.name } : null };
|
||||
})
|
||||
.sort((a, b) => b.prom - a.prom);
|
||||
}
|
||||
|
||||
export function bucketActividad(diasSinActividad) {
|
||||
if (diasSinActividad == null) return "Sin dato";
|
||||
if (diasSinActividad <= 14) return "Activa";
|
||||
if (diasSinActividad <= 30) return "Tibia";
|
||||
if (diasSinActividad <= 60) return "Fría";
|
||||
return "Congelada";
|
||||
}
|
||||
|
||||
// row: objeto ya con etiquetas resueltas (tipo, plan como texto, no option-set numérico).
|
||||
// faseInfo: { fase, started } | undefined, de alfa_stagedurations.
|
||||
// today: Date, para calcular días en fase de forma determinística.
|
||||
export function derivePipelineRow(row, faseInfo, today) {
|
||||
const plan = row.plan || "Sin plan de cierre";
|
||||
const peso = PESO_PLAN[plan] ?? 0.1;
|
||||
const est = row.est || 0;
|
||||
const diasEnFase = faseInfo?.started
|
||||
? Math.round((today - new Date(faseInfo.started)) / 86400000)
|
||||
: null;
|
||||
const estanc = (row.dsa != null && row.dsa > 14) || (diasEnFase != null && diasEnFase > 30);
|
||||
|
||||
return {
|
||||
...row,
|
||||
plan,
|
||||
peso,
|
||||
fc: +(est * peso).toFixed(2),
|
||||
estanc,
|
||||
faseActual: faseInfo?.fase || null,
|
||||
diasEnFase,
|
||||
actividad: bucketActividad(row.dsa),
|
||||
segmento: segmentoDe(row.tipo),
|
||||
calidad: calidadDe(row.clasif),
|
||||
mov: estanc ? "Estancada" : "En movimiento",
|
||||
mesCierre: row.close ? row.close.slice(0, 7) : null,
|
||||
};
|
||||
}
|
||||
54
app/lib/filterState.js
Normal file
54
app/lib/filterState.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// Estado de filtro multi-dimensión, codificado en el searchParam `f` como `dim:valor,dim2:valor2`
|
||||
// (equivalente al objeto global `filt` de App Informe/assets/js/state.js). Se parsea/filtra en el
|
||||
// servidor; los componentes cliente (FilterableRow, FilterChips) solo arman la URL nueva.
|
||||
|
||||
const SEP_DIM = ",";
|
||||
const SEP_KV = ":";
|
||||
|
||||
// Nota: NO se usa encodeURIComponent acá — URLSearchParams ya percent-codifica el valor completo
|
||||
// del param `f` al armar la query string (y lo decodifica solo al leerlo con .get()). Codificar acá
|
||||
// además duplicaría el escapado ("%3A" -> "%253A"). Limitación aceptada: un valor de campo que
|
||||
// contenga literalmente "," o ":" rompería el parseo — ningún dato real de ALFA+ los usa hoy.
|
||||
export function parseFiltParam(f) {
|
||||
const filt = {};
|
||||
if (!f) return filt;
|
||||
for (const part of f.split(SEP_DIM)) {
|
||||
const i = part.indexOf(SEP_KV);
|
||||
if (i === -1) continue;
|
||||
const dim = part.slice(0, i);
|
||||
const val = part.slice(i + 1);
|
||||
if (dim && val) filt[dim] = val;
|
||||
}
|
||||
return filt;
|
||||
}
|
||||
|
||||
export function encodeFiltParam(filt) {
|
||||
const entries = Object.entries(filt).filter(([, v]) => v);
|
||||
if (!entries.length) return "";
|
||||
return entries.map(([k, v]) => `${k}${SEP_KV}${v}`).join(SEP_DIM);
|
||||
}
|
||||
|
||||
// Mismo criterio AND que pipeF() del sitio HTML: cada dimensión filtrada exige igualdad exacta.
|
||||
// "(sin dato)" (el bucket que agg() usa para valores vacíos) matchea contra o[dim] vacío/null.
|
||||
export function applyFilt(arr, filt) {
|
||||
const entries = Object.entries(filt);
|
||||
if (!entries.length) return arr;
|
||||
return arr.filter((o) => entries.every(([dim, val]) => (o[dim] || "(sin dato)") === val));
|
||||
}
|
||||
|
||||
// Toggle de uno o varios ejes a la vez (una fila de panel = 1 par, una celda de matriz = 2 pares).
|
||||
// Si TODOS los pares ya están activos, el clic los quita; si no, los fija todos de golpe (mismo
|
||||
// comportamiento "todo o nada" que bindRows()/bindMatriz*() del HTML).
|
||||
export function toggleFilt(filt, pairs) {
|
||||
const allActive = pairs.every(([dim, val]) => filt[dim] === val);
|
||||
const next = { ...filt };
|
||||
pairs.forEach(([dim, val]) => {
|
||||
if (allActive) delete next[dim];
|
||||
else next[dim] = val;
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
export function isFiltActive(filt, pairs) {
|
||||
return pairs.every(([dim, val]) => filt[dim] === val);
|
||||
}
|
||||
34
app/lib/metas.js
Normal file
34
app/lib/metas.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import db from "./db";
|
||||
|
||||
// Metas mensuales — SQLite (Etapa 4). Clave: correo del vendedor, resuelto en vivo
|
||||
// contra systemusers (no hay una lista fija de correos confirmados — ver migration.md §11.5).
|
||||
// La tabla arranca vacía: un administrador las carga desde /admin/metas.
|
||||
|
||||
export function getMetas() {
|
||||
const rows = db.prepare("SELECT email, monto FROM metas").all();
|
||||
const map = {};
|
||||
rows.forEach((r) => {
|
||||
map[r.email] = r.monto;
|
||||
});
|
||||
return map;
|
||||
}
|
||||
|
||||
export function getMetaGlobal() {
|
||||
const row = db.prepare("SELECT valor FROM config WHERE clave = 'meta_global'").get();
|
||||
if (row) return Number(row.valor);
|
||||
return Object.values(getMetas()).reduce((a, v) => a + v, 0);
|
||||
}
|
||||
|
||||
export function setMeta(email, monto) {
|
||||
db.prepare(
|
||||
`INSERT INTO metas (email, monto, updated_at) VALUES (?, ?, datetime('now'))
|
||||
ON CONFLICT(email) DO UPDATE SET monto = excluded.monto, updated_at = excluded.updated_at`
|
||||
).run(email.toLowerCase(), monto);
|
||||
}
|
||||
|
||||
export function setMetaGlobal(monto) {
|
||||
db.prepare(
|
||||
`INSERT INTO config (clave, valor) VALUES ('meta_global', ?)
|
||||
ON CONFLICT(clave) DO UPDATE SET valor = excluded.valor`
|
||||
).run(String(monto));
|
||||
}
|
||||
90
app/lib/periodos.js
Normal file
90
app/lib/periodos.js
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
// Selector de período por fecha de cierre real (actualclosedate) — compartido por Resumen, Ganadas
|
||||
// y Perdemos. Ventana [from, to) en "YYYY-MM-DD", lista para pasar a getClosedRange().
|
||||
|
||||
export const PERIODOS = [
|
||||
{ k: "mes", lbl: "Este mes" },
|
||||
{ k: "semana", lbl: "Esta semana" },
|
||||
{ k: "mesAnt", lbl: "Mes anterior" },
|
||||
{ k: "semanaAnt", lbl: "Semana anterior" },
|
||||
];
|
||||
|
||||
export function periodoActivo(k) {
|
||||
return PERIODOS.some((p) => p.k === k) ? k : "mes";
|
||||
}
|
||||
|
||||
function isoDate(d) {
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
function addDays(d, n) {
|
||||
const r = new Date(d);
|
||||
r.setDate(r.getDate() + n);
|
||||
return r;
|
||||
}
|
||||
// Lunes de la semana de `d` — semana comercial Lun-Dom.
|
||||
function mondayOf(d) {
|
||||
const r = new Date(d);
|
||||
const day = r.getDay(); // 0=Dom, 1=Lun, ...
|
||||
r.setDate(r.getDate() + (day === 0 ? -6 : 1 - day));
|
||||
r.setHours(0, 0, 0, 0);
|
||||
return r;
|
||||
}
|
||||
|
||||
// mensual: true si el período es un mes calendario completo — la meta (metas.json) es mensual, así
|
||||
// que el cumplimiento de meta solo es comparable en esos períodos, no en semana/semana anterior.
|
||||
export function rangoDePeriodo(periodo) {
|
||||
const hoy = new Date();
|
||||
if (periodo === "semana") {
|
||||
const ini = mondayOf(hoy);
|
||||
return { from: isoDate(ini), to: isoDate(addDays(ini, 7)), lbl: "esta semana", mensual: false };
|
||||
}
|
||||
if (periodo === "semanaAnt") {
|
||||
const iniEsta = mondayOf(hoy);
|
||||
const ini = addDays(iniEsta, -7);
|
||||
return { from: isoDate(ini), to: isoDate(iniEsta), lbl: "la semana anterior", mensual: false };
|
||||
}
|
||||
if (periodo === "mesAnt") {
|
||||
const iniEste = new Date(hoy.getFullYear(), hoy.getMonth(), 1);
|
||||
const ini = new Date(hoy.getFullYear(), hoy.getMonth() - 1, 1);
|
||||
return { from: isoDate(ini), to: isoDate(iniEste), lbl: "el mes anterior", mensual: true };
|
||||
}
|
||||
const ini = new Date(hoy.getFullYear(), hoy.getMonth(), 1);
|
||||
const fin = new Date(hoy.getFullYear(), hoy.getMonth() + 1, 1);
|
||||
return { from: isoDate(ini), to: isoDate(fin), lbl: "este mes", mensual: true };
|
||||
}
|
||||
|
||||
// Selector de período para Previsión de Ventas — a diferencia de rangoDePeriodo() (hacia atrás,
|
||||
// sobre actualclosedate), este mira hacia adelante sobre estimatedclosedate ("Atrasadas" queda
|
||||
// aparte, calculado directo en prevision/page.js). [from, to) — to exclusivo; finIncl (to - 1 día)
|
||||
// es lo que espera decorarActividadVentana() (derive.js), que usa límites inclusivos.
|
||||
export const PERIODOS_PREVISION = [
|
||||
{ k: "mes", lbl: "Este mes" },
|
||||
{ k: "semana", lbl: "Esta semana" },
|
||||
{ k: "mesProx", lbl: "Próximo mes" },
|
||||
{ k: "semanaProx", lbl: "Próxima semana" },
|
||||
];
|
||||
|
||||
export function periodoPrevisionActivo(k) {
|
||||
return PERIODOS_PREVISION.some((p) => p.k === k) ? k : "mes";
|
||||
}
|
||||
|
||||
export function rangoDePeriodoPrevision(periodo) {
|
||||
const hoy = new Date();
|
||||
if (periodo === "semana") {
|
||||
const ini = mondayOf(hoy);
|
||||
const to = addDays(ini, 7);
|
||||
return { from: isoDate(ini), to: isoDate(to), finIncl: isoDate(addDays(to, -1)), lbl: "esta semana" };
|
||||
}
|
||||
if (periodo === "semanaProx") {
|
||||
const ini = addDays(mondayOf(hoy), 7);
|
||||
const to = addDays(ini, 7);
|
||||
return { from: isoDate(ini), to: isoDate(to), finIncl: isoDate(addDays(to, -1)), lbl: "la próxima semana" };
|
||||
}
|
||||
if (periodo === "mesProx") {
|
||||
const ini = new Date(hoy.getFullYear(), hoy.getMonth() + 1, 1);
|
||||
const to = new Date(hoy.getFullYear(), hoy.getMonth() + 2, 1);
|
||||
return { from: isoDate(ini), to: isoDate(to), finIncl: isoDate(addDays(to, -1)), lbl: "el próximo mes" };
|
||||
}
|
||||
const ini = new Date(hoy.getFullYear(), hoy.getMonth(), 1);
|
||||
const to = new Date(hoy.getFullYear(), hoy.getMonth() + 1, 1);
|
||||
return { from: isoDate(ini), to: isoDate(to), finIncl: isoDate(addDays(to, -1)), lbl: "este mes" };
|
||||
}
|
||||
440
app/lib/plan.js
Normal file
440
app/lib/plan.js
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
// 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"]);
|
||||
|
||||
// Tipos de actividad de una fila, en orden fijo, con cuántas hay de cada uno: [{ tipo: "Cita", n: 1 }, ...].
|
||||
function contarTipos(acts) {
|
||||
const m = {};
|
||||
acts.forEach((a) => {
|
||||
m[a.tipo] = (m[a.tipo] || 0) + 1;
|
||||
});
|
||||
return ["Cita", "Llamada", "Tarea"].filter((t) => m[t]).map((t) => ({ tipo: t, n: m[t] }));
|
||||
}
|
||||
|
||||
// A qué (oportunidad / caso / cuenta) y a qué sección pertenece una actividad; null si no entra al
|
||||
// plan (sin referente comercial, o del grupo Administrativo). Compartido por el plan de un día y el
|
||||
// de un período (Plan de Actividades).
|
||||
function clasificar(a) {
|
||||
if (a.estado === "cancelada") return null;
|
||||
if (a.objetivo && OBJ_ADMIN.has(a.objetivo)) return null;
|
||||
if (a.oportunidad) {
|
||||
return { ref: { ...a.oportunidad, etn: "opportunity" }, sec: seccionDeOportunidad(a) };
|
||||
}
|
||||
if (a.referente && REF_SIN_OPP.has(a.referente.tipo)) {
|
||||
return {
|
||||
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),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 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 (diaDe(a) !== dia) continue;
|
||||
const c = clasificar(a);
|
||||
if (!c) continue;
|
||||
const { ref, sec } = c;
|
||||
|
||||
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, tipos: contarTipos(r.acts) };
|
||||
})
|
||||
.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 por período (Plan de Actividades: semana y mes) -------------------------------------
|
||||
|
||||
export const PERIODOS_ACT = [
|
||||
{ k: "semana_pasada", lbl: "Semana pasada" },
|
||||
{ k: "semana", lbl: "Esta semana" },
|
||||
{ k: "semana_proxima", lbl: "Próxima semana" },
|
||||
{ k: "mes_pasado", lbl: "Mes pasado" },
|
||||
{ k: "mes", lbl: "Este mes" },
|
||||
];
|
||||
|
||||
export function periodoActActivo(k) {
|
||||
return PERIODOS_ACT.some((p) => p.k === k) ? k : "semana";
|
||||
}
|
||||
|
||||
// Rango [desde, hasta] (ambos incluidos, "YYYY-MM-DD"). Semana comercial lunes–domingo.
|
||||
export function rangoPeriodoAct(k, hoy) {
|
||||
if (k.startsWith("semana")) {
|
||||
const base = semanaDe(hoy).lunes;
|
||||
const lunes = k === "semana_pasada" ? addDays(base, -7) : k === "semana_proxima" ? addDays(base, 7) : base;
|
||||
return { tipo: "semana", desde: lunes, hasta: addDays(lunes, 6) };
|
||||
}
|
||||
const [y, m] = hoy.split("-").map(Number);
|
||||
const off = k === "mes_pasado" ? -1 : 0;
|
||||
const primero = new Date(Date.UTC(y, m - 1 + off, 1));
|
||||
const ultimo = new Date(Date.UTC(y, m + off, 0));
|
||||
return { tipo: "mes", desde: primero.toISOString().slice(0, 10), hasta: ultimo.toISOString().slice(0, 10) };
|
||||
}
|
||||
|
||||
export function diasDelRango(desde, hasta) {
|
||||
const out = [];
|
||||
for (let d = desde; d <= hasta; d = addDays(d, 1)) out.push(d);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const esHabil = (iso) => {
|
||||
const dow = new Date(iso + "T12:00:00Z").getUTCDay();
|
||||
return dow >= 1 && dow <= 5;
|
||||
};
|
||||
|
||||
const DIAS_CORTOS = ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"];
|
||||
// «Lun 26»
|
||||
export const diaCorto = (iso) => `${DIAS_CORTOS[new Date(iso + "T12:00:00Z").getUTCDay()]} ${Number(iso.slice(8, 10))}`;
|
||||
// «Lun» (para las fichas de la franja)
|
||||
export const diaSemana = (iso) => DIAS_CORTOS[new Date(iso + "T12:00:00Z").getUTCDay()];
|
||||
|
||||
// Plan de un período: las mismas 5 secciones que el plan del día (una fila por oportunidad/caso/cuenta
|
||||
// y propietario para TODO el período, con los días en que tiene actividad), más la cobertura por día y
|
||||
// por ejecutivo y los indicadores de cumplimiento.
|
||||
// Cumplimiento «a la fecha» = completadas ÷ lo que ya debía estar hecho = actividades de días ANTERIORES
|
||||
// a hoy (hoy todavía no termina, así que a las 10 a. m. no cuenta como incumplido; el avance de hoy se
|
||||
// ve en el Plan del Día). El universo son las actividades que entran al plan (ligadas a oportunidad,
|
||||
// caso o cuenta, sin las administrativas).
|
||||
export function armarPlanPeriodo(actividades, desde, hasta, hoy) {
|
||||
const filas = new Map();
|
||||
const elegibles = [];
|
||||
for (const a of actividades) {
|
||||
const dia = diaDe(a);
|
||||
if (!dia || dia < desde || dia > hasta) continue;
|
||||
const c = clasificar(a);
|
||||
if (!c) continue;
|
||||
elegibles.push({ a, dia });
|
||||
const { ref, sec } = c;
|
||||
const key = `${ref.id}|${a.owner}`;
|
||||
let r = filas.get(key);
|
||||
if (!r) {
|
||||
r = { key, sec, owner: a.owner, opp: ref, objetivos: [], acts: [], dias: [] };
|
||||
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);
|
||||
if (!r.dias.includes(dia)) r.dias.push(dia);
|
||||
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;
|
||||
const vencidas = r.acts.filter((a) => a.estado !== "completada" && diaDe(a) < hoy).length;
|
||||
const estado = hechas === total ? "Completada" : vencidas > 0 ? "Vencida" : hechas > 0 ? "En curso" : "Pendiente";
|
||||
return { ...r, dias: [...r.dias].sort(), hechas, total, vencidas, estado, tipos: contarTipos(r.acts) };
|
||||
})
|
||||
.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),
|
||||
actTotal: rows.reduce((t, r) => t + r.total, 0),
|
||||
actHechas: rows.reduce((t, r) => t + r.hechas, 0),
|
||||
};
|
||||
});
|
||||
|
||||
const porDia = {};
|
||||
const porOwner = {};
|
||||
for (const { a, dia } of elegibles) {
|
||||
const hecha = a.estado === "completada";
|
||||
const d = (porDia[dia] ||= { total: 0, hechas: 0 });
|
||||
d.total++;
|
||||
if (hecha) d.hechas++;
|
||||
const o = (porOwner[a.owner] ||= { total: 0, hechas: 0, debidas: 0, debidasHechas: 0, vencidas: 0, porDia: {} });
|
||||
o.total++;
|
||||
if (hecha) o.hechas++;
|
||||
o.porDia[dia] = (o.porDia[dia] || 0) + 1;
|
||||
if (dia < hoy) {
|
||||
o.debidas++;
|
||||
if (hecha) o.debidasHechas++;
|
||||
}
|
||||
if (!hecha && dia < hoy) o.vencidas++;
|
||||
}
|
||||
|
||||
const total = elegibles.length;
|
||||
const hechas = elegibles.filter(({ a }) => a.estado === "completada").length;
|
||||
const debidas = elegibles.filter(({ dia }) => dia < hoy);
|
||||
const debidasHechas = debidas.filter(({ a }) => a.estado === "completada").length;
|
||||
const vencidas = elegibles.filter(({ a, dia }) => a.estado !== "completada" && dia < hoy).length;
|
||||
const habiles = diasDelRango(desde, hasta).filter(esHabil);
|
||||
const diasSinActividad = habiles.filter((d) => !porDia[d]).length;
|
||||
return {
|
||||
secciones,
|
||||
porDia,
|
||||
porOwner,
|
||||
resumen: {
|
||||
agendadas: total,
|
||||
hechas,
|
||||
debidas: debidas.length,
|
||||
debidasHechas,
|
||||
vencidas,
|
||||
diasHabiles: habiles.length,
|
||||
diasSinActividad,
|
||||
pctFecha: debidas.length ? Math.round((debidasHechas / debidas.length) * 1000) / 10 : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Objetivo de actividad sugerido según la etapa de forecast de la oportunidad (guía de planificación
|
||||
// validada por Marco el 2026-10-26; es una orientación, no una obligación). Las renovaciones llevan
|
||||
// «Renovación» en cualquier etapa. Los nombres son los del catálogo de Objetivo de Actividad.
|
||||
const OBJETIVO_POR_ETAPA = {
|
||||
20: "Diagnosticar Necesidades",
|
||||
40: "Presentación de Servicio",
|
||||
50: "Presentar Oferta",
|
||||
60: "Negociación",
|
||||
70: "Negociación",
|
||||
80: "Firma Contrato-Adendum",
|
||||
90: "Firma Contrato-Adendum",
|
||||
};
|
||||
export function objetivoSugerido(o) {
|
||||
if (COD_RENOVACION.has(o.tipoCodigo)) return "Renovación";
|
||||
const pct = parseInt(o.forecast || "", 10) || 0;
|
||||
return OBJETIVO_POR_ETAPA[pct] || null;
|
||||
}
|
||||
|
||||
// Huecos de planificación de un período: oportunidades abiertas con cierre estimado en el período y
|
||||
// ninguna actividad en TODO el período, ordenadas por prioridad (primero las de forecast 80% y 90%,
|
||||
// luego por valor) para que quien planifica sepa qué agendar primero.
|
||||
export function sinActividadPeriodo(opps, actividades, desde, hasta) {
|
||||
const conActividad = new Set();
|
||||
for (const a of actividades) {
|
||||
if (a.estado === "cancelada" || !a.oportunidad) continue;
|
||||
const dia = diaDe(a);
|
||||
if (dia && dia >= desde && dia <= hasta) conActividad.add(a.oportunidad.id);
|
||||
}
|
||||
return opps
|
||||
.filter((o) => !conActividad.has(o.id))
|
||||
.map((o) => {
|
||||
const pct = parseInt(o.forecast || "", 10) || 0;
|
||||
return { ...o, pct, prioridadAlta: pct >= 80 };
|
||||
})
|
||||
.sort((x, y) => y.pct - x.pct || y.valor - x.valor || x.cierre.localeCompare(y.cierre));
|
||||
}
|
||||
|
||||
// ---- 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 };
|
||||
}
|
||||
67
app/lib/planCerrado.js
Normal file
67
app/lib/planCerrado.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import db from "./db";
|
||||
|
||||
// "Plan cerrado" (Plan del Día, etapa 3): foto del plan de un ejecutivo en un día, guardada cuando
|
||||
// el ejecutivo (o el administrador) pulsa «Marcar plan como listo». Sirve para el coaching: comparar
|
||||
// lo que se planeó contra lo que pasó. Marcar de nuevo guarda una VERSIÓN nueva (se conserva el
|
||||
// historial); la vista de coaching usa la última por defecto.
|
||||
//
|
||||
// La tabla se crea aquí (IF NOT EXISTS) y no en db.js: db.js se evalúa una sola vez por proceso
|
||||
// (globalThis.__informeDb), así que una tabla agregada allí no existiría hasta reiniciar el servidor.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS plan_cerrado (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
fecha TEXT NOT NULL,
|
||||
owner_id TEXT NOT NULL,
|
||||
owner_name TEXT NOT NULL,
|
||||
marcado_por TEXT NOT NULL,
|
||||
marcado_en TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
snapshot TEXT NOT NULL,
|
||||
UNIQUE (fecha, owner_id, version)
|
||||
);
|
||||
`);
|
||||
|
||||
// ownerId = systemuserid de Dynamics (estable aunque la persona entre con @alfa.com.ni o con su UPN).
|
||||
export function guardarPlanCerrado({ fecha, ownerId, ownerName, marcadoPor, snapshot }) {
|
||||
const tx = db.transaction(() => {
|
||||
const row = db.prepare("SELECT MAX(version) AS v FROM plan_cerrado WHERE fecha = ? AND owner_id = ?").get(fecha, ownerId);
|
||||
const version = (row?.v || 0) + 1;
|
||||
db.prepare(
|
||||
`INSERT INTO plan_cerrado (fecha, owner_id, owner_name, marcado_por, marcado_en, version, snapshot)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
||||
).run(fecha, ownerId, ownerName, marcadoPor, new Date().toISOString(), version, JSON.stringify(snapshot));
|
||||
return version;
|
||||
});
|
||||
return tx();
|
||||
}
|
||||
|
||||
export function getVersionesPlan(fecha, ownerId) {
|
||||
return db
|
||||
.prepare("SELECT version, marcado_en, marcado_por FROM plan_cerrado WHERE fecha = ? AND owner_id = ? ORDER BY version")
|
||||
.all(fecha, ownerId);
|
||||
}
|
||||
|
||||
// version omitida = la última.
|
||||
export function getPlanCerrado(fecha, ownerId, version) {
|
||||
const row = version
|
||||
? db.prepare("SELECT * FROM plan_cerrado WHERE fecha = ? AND owner_id = ? AND version = ?").get(fecha, ownerId, version)
|
||||
: db.prepare("SELECT * FROM plan_cerrado WHERE fecha = ? AND owner_id = ? ORDER BY version DESC LIMIT 1").get(fecha, ownerId);
|
||||
if (!row) return null;
|
||||
return { ...row, snapshot: JSON.parse(row.snapshot) };
|
||||
}
|
||||
|
||||
// Último plan marcado de cada ejecutivo en un día: { [owner_id]: { version, marcado_en } } — para la
|
||||
// columna «Plan listo» del resumen del equipo.
|
||||
export function getPlanesListosDelDia(fecha) {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT owner_id, version, marcado_en FROM plan_cerrado p
|
||||
WHERE fecha = ? AND version = (SELECT MAX(version) FROM plan_cerrado WHERE fecha = p.fecha AND owner_id = p.owner_id)`
|
||||
)
|
||||
.all(fecha);
|
||||
const map = {};
|
||||
rows.forEach((r) => {
|
||||
map[r.owner_id] = { version: r.version, marcado_en: r.marcado_en };
|
||||
});
|
||||
return map;
|
||||
}
|
||||
479
app/lib/queries.js
Normal file
479
app/lib/queries.js
Normal file
|
|
@ -0,0 +1,479 @@
|
|||
import { dv, fv, lookupType, odataString } from "./dataverse";
|
||||
import { derivePipelineRow, segmentoDe, normComp, normalizarFase, EJECUTIVOS_VENTA, OBJETIVO_A_ETAPA } from "./derive";
|
||||
|
||||
const OPP_SELECT = [
|
||||
"opportunityid",
|
||||
"name",
|
||||
"_ownerid_value",
|
||||
"alfa_typeopportunity",
|
||||
"alfa_tipodeventa",
|
||||
"_alfa_lineadenegocioid_value",
|
||||
"_alfa_servicioproductoid_value",
|
||||
"estimatedvalue",
|
||||
"actualvalue",
|
||||
"alfa_plandecierre",
|
||||
"alfa_envejecimiento",
|
||||
"alfa_diassinactividad",
|
||||
"estimatedclosedate",
|
||||
"actualclosedate",
|
||||
"stepname",
|
||||
"alfa_estadodelanegociacion",
|
||||
"_customerid_value",
|
||||
"_campaignid_value",
|
||||
"_alfa_competidorid_value",
|
||||
"alfa_puntuaciondelaoportunidad",
|
||||
"alfa_niveldeoportunidadestrellas",
|
||||
"alfa_clasificaciondeoportunidad",
|
||||
"alfa_luzamarilla",
|
||||
"msdyn_forecastcategory",
|
||||
"prioritycode",
|
||||
].join(",");
|
||||
|
||||
// Tubería: 5 tipos de la cartera "en pipeline" (ver ALFA_Estructura_Oportunidades_CRM.md).
|
||||
const PIPE_TYPE_FILTER =
|
||||
"(alfa_typeopportunity eq 100000000 or alfa_typeopportunity eq 100000003 or " +
|
||||
"alfa_typeopportunity eq 100000004 or alfa_typeopportunity eq 100000007 or alfa_typeopportunity eq 100000009)";
|
||||
|
||||
// Renovaciones: Contrato Vencido (100000002) y Próximo a Vencer 30/60/90 (100000001) — universo
|
||||
// aparte de Ventas, no cuenta para cumplimiento de meta (ver CLAUDE.md).
|
||||
export const REN_TYPE_FILTER = "(alfa_typeopportunity eq 100000001 or alfa_typeopportunity eq 100000002)";
|
||||
|
||||
// Ventas ganadas/perdidas: los mismos 4 tipos que cuentan para cumplimiento de meta (TIPOS_META,
|
||||
// derive.js) — excluye Contrato Nuevo Vecinos (100000009, cuenta para Tubería pero no es un tipo
|
||||
// de meta), renovaciones y SAC-Retención/Traslado/Otros. Se aplica a won Y a lost (mismo criterio
|
||||
// que VENTA_TIPOS en herramientas/build_all_months.js del sitio HTML).
|
||||
export const VENTA_TYPE_FILTER =
|
||||
"(alfa_typeopportunity eq 100000000 or alfa_typeopportunity eq 100000003 or " +
|
||||
"alfa_typeopportunity eq 100000004 or alfa_typeopportunity eq 100000007)";
|
||||
|
||||
function chunk(arr, size) {
|
||||
const out = [];
|
||||
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function getSystemUsers(accessToken) {
|
||||
const data = await dv(
|
||||
"systemusers?$select=systemuserid,fullname,internalemailaddress&$filter=isdisabled eq false",
|
||||
accessToken
|
||||
);
|
||||
return (data.value || []).map((u) => ({
|
||||
id: u.systemuserid,
|
||||
name: u.fullname,
|
||||
email: (u.internalemailaddress || "").toLowerCase(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Un usuario puede entrar con @alfa.com.ni o con su UPN @alfaonline365.onmicrosoft.com, y en
|
||||
// Dynamics el primero suele estar en internalemailaddress y el segundo en domainname. Se busca por
|
||||
// ambos campos y por los dos dominios para que cualquiera de los correos resuelva al mismo usuario.
|
||||
const DOMINIOS_ALFA = ["alfa.com.ni", "alfaonline365.onmicrosoft.com"];
|
||||
|
||||
function variantesCorreo(email) {
|
||||
const e = email.trim().toLowerCase();
|
||||
const [local, dominio] = e.split("@");
|
||||
if (!local || !DOMINIOS_ALFA.includes(dominio)) return [e];
|
||||
return DOMINIOS_ALFA.map((d) => `${local}@${d}`);
|
||||
}
|
||||
|
||||
export async function resolveOwnerId(email, accessToken) {
|
||||
if (!email) return null;
|
||||
const cond = variantesCorreo(email)
|
||||
.flatMap((v) => [`internalemailaddress eq '${odataString(v)}'`, `domainname eq '${odataString(v)}'`])
|
||||
.join(" or ");
|
||||
const data = await dv(
|
||||
`systemusers?$select=systemuserid&$filter=${encodeURIComponent(`(${cond})`)}`,
|
||||
accessToken
|
||||
);
|
||||
return data.value?.[0]?.systemuserid || null;
|
||||
}
|
||||
|
||||
function mapOpportunityRow(o) {
|
||||
const tipo = fv(o, "alfa_typeopportunity");
|
||||
return {
|
||||
id: o.opportunityid,
|
||||
name: o.name,
|
||||
owner: fv(o, "_ownerid_value"),
|
||||
tipo,
|
||||
segmento: segmentoDe(tipo),
|
||||
origen: fv(o, "alfa_tipodeventa"),
|
||||
linea: fv(o, "_alfa_lineadenegocioid_value"),
|
||||
servicio: fv(o, "_alfa_servicioproductoid_value"),
|
||||
est: o.estimatedvalue || 0,
|
||||
actual: o.actualvalue || 0,
|
||||
plan: fv(o, "alfa_plandecierre"),
|
||||
env: o.alfa_envejecimiento ?? null,
|
||||
dsa: o.alfa_diassinactividad ?? null,
|
||||
close: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null,
|
||||
actualClose: o.actualclosedate ? o.actualclosedate.slice(0, 10) : null,
|
||||
step: o.stepname,
|
||||
estado: o.alfa_estadodelanegociacion || null,
|
||||
cliente: fv(o, "_customerid_value"),
|
||||
campaign: fv(o, "_campaignid_value"),
|
||||
score: o.alfa_puntuaciondelaoportunidad ?? null,
|
||||
estrellas: o.alfa_niveldeoportunidadestrellas ?? null,
|
||||
clasif: fv(o, "alfa_clasificaciondeoportunidad") || "Sin clasificar",
|
||||
luz: fv(o, "alfa_luzamarilla") || "Sin registrar",
|
||||
competidor: normComp(fv(o, "_alfa_competidorid_value")),
|
||||
// Escala propia de ALFA+ (NO el forecastcategory estándar de Dynamics — ver CLAUDE.md):
|
||||
// la etiqueta ya trae el % adelante ("20% Calificada" … "90% Firma de contrato"), de ahí se
|
||||
// deriva el orden sin mantener un mapa aparte.
|
||||
prev: fv(o, "msdyn_forecastcategory") || "Sin categoría",
|
||||
prevPct: parseInt(fv(o, "msdyn_forecastcategory") || "", 10) || 0,
|
||||
// Prioridad: campo propio de Dynamics (`prioritycode`), la fija el ejecutivo; no se calcula.
|
||||
prioridad: fv(o, "prioritycode") || "Sin prioridad",
|
||||
};
|
||||
}
|
||||
|
||||
async function getFaseActual(oppIds, accessToken) {
|
||||
const fase = {};
|
||||
for (const batch of chunk(oppIds, 150)) {
|
||||
if (!batch.length) continue;
|
||||
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
|
||||
const fetchXml =
|
||||
`<fetch><entity name="alfa_stageduration">` +
|
||||
`<attribute name="alfa_subject"/><attribute name="alfa_started"/><attribute name="alfa_opportunity"/>` +
|
||||
`<filter><condition attribute="statuscode" operator="eq" value="1"/>` +
|
||||
`<condition attribute="alfa_opportunity" operator="in">${conditions}</condition></filter>` +
|
||||
`</entity></fetch>`;
|
||||
const data = await dv(`alfa_stagedurations?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
|
||||
for (const r of data.value || []) {
|
||||
const oid = r["_alfa_opportunity_value"] || r.alfa_opportunity;
|
||||
const started = r.alfa_started;
|
||||
const subj = normalizarFase((r.alfa_subject || "").replace("Fase: ", ""));
|
||||
if (!fase[oid] || (started && started > fase[oid].started)) {
|
||||
fase[oid] = { fase: subj, started };
|
||||
}
|
||||
}
|
||||
}
|
||||
return fase;
|
||||
}
|
||||
|
||||
// Historial completo de fases COMPLETADAS por oportunidad (a diferencia de getFaseActual(), que
|
||||
// solo trae la fase en curso) — para Velocidad de movimiento (pipeVelFor(), derive.js). statuscode
|
||||
// eq 100000000 = "Completado" en este tenant (confirmado en herramientas/build_pipevel.js del
|
||||
// sitio HTML) — excluye la fase activa, aún sin cerrar, de cada oportunidad.
|
||||
export async function getStageDurations(oppIds, accessToken) {
|
||||
// Oferta/Cotización/Proponer son una sola fase: si una oportunidad pasó por dos de ellas, se suman
|
||||
// sus duraciones en un único tramo (clave oportunidad+fase) para no contarla dos veces.
|
||||
const tramos = new Map();
|
||||
for (const batch of chunk(oppIds, 150)) {
|
||||
if (!batch.length) continue;
|
||||
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
|
||||
const fetchXml =
|
||||
`<fetch><entity name="alfa_stageduration">` +
|
||||
`<attribute name="alfa_subject"/><attribute name="alfa_duration"/><attribute name="alfa_opportunity"/>` +
|
||||
`<filter><condition attribute="statuscode" operator="eq" value="100000000"/>` +
|
||||
`<condition attribute="alfa_opportunity" operator="in">${conditions}</condition></filter>` +
|
||||
`</entity></fetch>`;
|
||||
const data = await dv(`alfa_stagedurations?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
|
||||
for (const r of data.value || []) {
|
||||
const oppId = r["_alfa_opportunity_value"] || r.alfa_opportunity;
|
||||
if (!oppId || r.alfa_duration == null) continue;
|
||||
const subj = (r.alfa_subject || "").replace("Fase: ", "");
|
||||
if (!subj || subj === "Ganada") continue; // no es un tramo de velocidad
|
||||
const fase = normalizarFase(subj);
|
||||
const k = `${oppId}|${fase}`;
|
||||
const t = tramos.get(k);
|
||||
if (t) t.dur += r.alfa_duration;
|
||||
else tramos.set(k, { oppId, fase, dur: r.alfa_duration });
|
||||
}
|
||||
}
|
||||
const out = [...tramos.values()];
|
||||
return out;
|
||||
}
|
||||
|
||||
// Motivo/competidor de cierre — viven en opportunityclose, no en opportunity (ver
|
||||
// contexto_tabla_cierre_oportunidad.md). alfa_motivodecierre es el campo principal (Alfa);
|
||||
// opportunitystatuscode es el respaldo estándar — en la práctica muchos cierres recientes
|
||||
// solo llenan el estándar. Nos quedamos con el cierre más reciente por oportunidad.
|
||||
export async function getMotivosCierre(oppIds, accessToken) {
|
||||
const motivos = {};
|
||||
for (const batch of chunk(oppIds, 150)) {
|
||||
if (!batch.length) continue;
|
||||
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
|
||||
const fetchXml =
|
||||
`<fetch><entity name="opportunityclose">` +
|
||||
`<attribute name="opportunityid"/><attribute name="alfa_motivodecierre"/>` +
|
||||
`<attribute name="opportunitystatuscode"/><attribute name="alfa_competitor"/>` +
|
||||
`<attribute name="createdon"/>` +
|
||||
`<filter><condition attribute="opportunityid" operator="in">${conditions}</condition></filter>` +
|
||||
`</entity></fetch>`;
|
||||
const data = await dv(`opportunitycloses?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
|
||||
for (const r of data.value || []) {
|
||||
const oid = r["_opportunityid_value"];
|
||||
const created = r.createdon;
|
||||
if (motivos[oid] && motivos[oid].createdon >= created) continue;
|
||||
motivos[oid] = {
|
||||
createdon: created,
|
||||
motivo: fv(r, "alfa_motivodecierre") || fv(r, "opportunitystatuscode") || null,
|
||||
competidor: fv(r, "_alfa_competitor_value"),
|
||||
};
|
||||
}
|
||||
}
|
||||
return motivos;
|
||||
}
|
||||
|
||||
// Resuelve una lista de emails a systemuserids (en paralelo) y arma la cláusula OR
|
||||
// `(_ownerid_value eq id1 or _ownerid_value eq id2 ...)` — multi-propietario, ver CLAUDE.md/authz.js.
|
||||
async function resolveOwnerIds(emails, accessToken) {
|
||||
const ids = await Promise.all(emails.map((e) => resolveOwnerId(e, accessToken)));
|
||||
return ids.filter(Boolean);
|
||||
}
|
||||
function ownerOrClause(ids) {
|
||||
return `(${ids.map((id) => `_ownerid_value eq ${id}`).join(" or ")})`;
|
||||
}
|
||||
|
||||
// scope: { emails, locked } de ownerFilter(). emails=[] (admin, "todos") no filtra por propietario.
|
||||
// typeFilter: PIPE_TYPE_FILTER (ventas, default) o REN_TYPE_FILTER (renovaciones).
|
||||
async function getPipelineOfType(accessToken, scope, typeFilter) {
|
||||
let filter = `statecode eq 0 and estimatedclosedate ne null and msdyn_forecastcategory ne 100000001 and ${typeFilter}`;
|
||||
if (scope.emails?.length) {
|
||||
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
|
||||
if (!ownerIds.length) return [];
|
||||
filter += ` and ${ownerOrClause(ownerIds)}`;
|
||||
}
|
||||
const data = await dv(
|
||||
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
|
||||
accessToken
|
||||
);
|
||||
const rows = (data.value || []).map(mapOpportunityRow);
|
||||
const faseMap = await getFaseActual(rows.map((r) => r.id), accessToken);
|
||||
const today = new Date();
|
||||
return rows.map((r) => derivePipelineRow(r, faseMap[r.id], today));
|
||||
}
|
||||
|
||||
export async function getPipeline(accessToken, scope) {
|
||||
return getPipelineOfType(accessToken, scope, PIPE_TYPE_FILTER);
|
||||
}
|
||||
|
||||
export async function getRenovPipeline(accessToken, scope) {
|
||||
return getPipelineOfType(accessToken, scope, REN_TYPE_FILTER);
|
||||
}
|
||||
|
||||
// Resuelve una sola vez los systemuserids del scope (o [] si no aplica) — para reusar en varias
|
||||
// llamadas a getClosed sin repetir la consulta a systemusers cada vez (ej. Tendencia, 6 meses).
|
||||
// scope.emails=[] ("todos") no filtra por propietario — cualquiera puede vender/renovar (incluida
|
||||
// gente sin rol oficial de ventas pero con permiso para ciertos clientes, ver CLAUDE.md); el
|
||||
// universo correcto de "ventas" lo da el typeFilter, no una lista fija de nombres.
|
||||
export async function resolveScopeOwnerIds(scope, accessToken) {
|
||||
if (!scope.emails?.length) return { none: true, ownerIds: [] };
|
||||
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
|
||||
return { none: false, ownerIds };
|
||||
}
|
||||
|
||||
// statecode: 1 = ganadas, 2 = perdidas. fromDate/toDate: "YYYY-MM-DD", ventana de cierre real
|
||||
// (actualclosedate) [fromDate, toDate). resolvedOwnerIds: opcional, ya resuelto vía
|
||||
// resolveScopeOwnerIds — evita resolver los emails en cada llamada. typeFilter: opcional — sin él,
|
||||
// trae cualquier tipo (Renovaciones pasa REN_TYPE_FILTER, Ventas pasa VENTA_TYPE_FILTER explícito).
|
||||
export async function getClosedRange(accessToken, scope, statecode, fromDate, toDate, resolvedOwnerIds, typeFilter) {
|
||||
let filter =
|
||||
`statecode eq ${statecode} and actualclosedate ge ${fromDate} and actualclosedate lt ${toDate}`;
|
||||
if (typeFilter) filter += ` and ${typeFilter}`;
|
||||
if (scope.emails?.length) {
|
||||
const ownerIds = resolvedOwnerIds !== undefined ? resolvedOwnerIds : await resolveOwnerIds(scope.emails, accessToken);
|
||||
if (!ownerIds.length) return [];
|
||||
filter += ` and ${ownerOrClause(ownerIds)}`;
|
||||
}
|
||||
const data = await dv(
|
||||
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
|
||||
accessToken
|
||||
);
|
||||
return (data.value || []).map(mapOpportunityRow);
|
||||
}
|
||||
|
||||
// month: "YYYY-MM" — atajo de getClosedRange() para el mes calendario completo.
|
||||
export async function getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, typeFilter) {
|
||||
const monthStart = `${month}-01`;
|
||||
const [y, m] = month.split("-").map(Number);
|
||||
const nextMonth = new Date(y, m, 1).toISOString().slice(0, 10);
|
||||
return getClosedRange(accessToken, scope, statecode, monthStart, nextMonth, resolvedOwnerIds, typeFilter);
|
||||
}
|
||||
|
||||
// Oportunidades abiertas (Ventas + Renovaciones) con cierre estimado en [desde, hasta] (fechas
|
||||
// "YYYY-MM-DD", ambas incluidas). Consulta liviana para "Plan del Día": sin fase ni puntuación.
|
||||
// Mismo filtro de forecast que la Tubería (excluye la categoría 0% Omitida, ver CLAUDE.md).
|
||||
export async function getOportunidadesSemana(accessToken, scope, desde, hasta) {
|
||||
const hastaExcl = new Date(hasta + "T12:00:00Z");
|
||||
hastaExcl.setUTCDate(hastaExcl.getUTCDate() + 1);
|
||||
let filter =
|
||||
`statecode eq 0 and estimatedclosedate ge ${desde} and estimatedclosedate lt ${hastaExcl.toISOString().slice(0, 10)}` +
|
||||
` and msdyn_forecastcategory ne 100000001 and (${PIPE_TYPE_FILTER} or ${REN_TYPE_FILTER})`;
|
||||
if (scope.emails?.length) {
|
||||
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
|
||||
if (!ownerIds.length) return [];
|
||||
filter += ` and ${ownerOrClause(ownerIds)}`;
|
||||
}
|
||||
const select = [
|
||||
"opportunityid", "name", "_ownerid_value", "_customerid_value", "estimatedvalue",
|
||||
"estimatedclosedate", "alfa_typeopportunity", "msdyn_forecastcategory",
|
||||
].join(",");
|
||||
const data = await dv(`opportunities?$select=${select}&$filter=${encodeURIComponent(filter)}&$top=1000`, accessToken);
|
||||
return (data.value || []).map((o) => ({
|
||||
id: o.opportunityid,
|
||||
nombre: o.name,
|
||||
owner: fv(o, "_ownerid_value") || "",
|
||||
cliente: fv(o, "_customerid_value"),
|
||||
valor: o.estimatedvalue || 0,
|
||||
cierre: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : "",
|
||||
tipoCodigo: o.alfa_typeopportunity ?? null,
|
||||
forecast: fv(o, "msdyn_forecastcategory"),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getRenovClosed(accessToken, scope, statecode, month, resolvedOwnerIds) {
|
||||
return getClosed(accessToken, scope, statecode, month, resolvedOwnerIds, REN_TYPE_FILTER);
|
||||
}
|
||||
|
||||
// Ventana de historia para Actividades: statecode eq 0 (abierta, sin tope — es un plan de trabajo
|
||||
// vivo) trae todo lo pendiente; scheduledend ge <cutoff> acota lo cerrado/cancelado a los últimos
|
||||
// 90 días para no traer años de historial en cada carga (mismo patrón que build_actividades.js del
|
||||
// sitio HTML, que usa un corte de fecha fijo en vez de "siempre todo").
|
||||
const ACTIVIDADES_DIAS_HISTORIA = 90;
|
||||
|
||||
const ACTIVIDAD_ENTIDADES = [
|
||||
{ entity: "tasks", tipo: "Tarea", navProp: "regardingobjectid_opportunity_task", propioField: "prioritycode", propioLabel: "Prioridad" },
|
||||
{ entity: "appointments", tipo: "Cita", navProp: "regardingobjectid_opportunity_appointment", propioField: "location", propioLabel: "Ubicación" },
|
||||
{ entity: "phonecalls", tipo: "Llamada", navProp: "regardingobjectid_opportunity_phonecall", propioField: "directioncode", propioLabel: "Dirección" },
|
||||
];
|
||||
|
||||
function estadoBase(statecode) {
|
||||
if (statecode === 1) return "completada";
|
||||
if (statecode === 2) return "cancelada";
|
||||
return "abierta"; // 0=Abierto, 3=Programado (Cita) — ambas "no cerradas" a efectos de negocio
|
||||
}
|
||||
|
||||
function mapActividadRow(r, tipo, navProp, propioField, propioLabel) {
|
||||
const tipoRef = lookupType(r, "_regardingobjectid_value");
|
||||
const nombreRef = fv(r, "_regardingobjectid_value");
|
||||
const objetivo = fv(r, "_alfa_objetivodeactividad_value");
|
||||
const opp = r[navProp];
|
||||
const propioValor = propioField === "location" ? r.location || null : fv(r, propioField);
|
||||
return {
|
||||
id: r.activityid,
|
||||
tipo,
|
||||
owner: fv(r, "_ownerid_value"),
|
||||
asunto: r.subject || "(sin asunto)",
|
||||
scheduledstart: r.scheduledstart || null,
|
||||
scheduledend: r.scheduledend || null,
|
||||
scheduledstartFmt: fv(r, "scheduledstart"),
|
||||
scheduledendFmt: fv(r, "scheduledend"),
|
||||
estado: estadoBase(r.statecode),
|
||||
objetivo,
|
||||
etapa: objetivo ? OBJETIVO_A_ETAPA[objetivo] || null : null,
|
||||
referente: tipoRef && nombreRef ? { tipo: tipoRef, nombre: nombreRef, id: r._regardingobjectid_value } : null,
|
||||
campoPropio: { label: propioLabel, valor: propioValor },
|
||||
ingresoEstimado: opp && typeof opp.estimatedvalue === "number" ? opp.estimatedvalue : null,
|
||||
tipoOportunidad: opp ? fv(opp, "alfa_typeopportunity") : null,
|
||||
// Datos de la oportunidad referida para "Plan del Día" (lib/plan.js): clasifica por tipo
|
||||
// (código crudo, no la etiqueta) y por forecast, y muestra cliente y valor.
|
||||
oportunidad: opp
|
||||
? {
|
||||
id: opp.opportunityid || r._regardingobjectid_value,
|
||||
nombre: opp.name || null,
|
||||
cliente: fv(opp, "_customerid_value"),
|
||||
valor: typeof opp.estimatedvalue === "number" ? opp.estimatedvalue : 0,
|
||||
tipoCodigo: opp.alfa_typeopportunity ?? null,
|
||||
forecast: fv(opp, "msdyn_forecastcategory"),
|
||||
cierre: opp.estimatedclosedate ? opp.estimatedclosedate.slice(0, 10) : null,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
// scope: { email, locked }. email null (admin, "todos") trae los ejecutivos de venta curados —
|
||||
// mismo alcance que el resto del informe (EJECUTIVOS_VENTA), resuelto en vivo contra systemusers
|
||||
// en vez de una tabla fija de GUID (que es lo que hacía el ETL estático y quedaba desactualizada).
|
||||
const COHORTE_SELECT = [
|
||||
"opportunityid", "name", "createdon", "statecode", "actualclosedate", "estimatedclosedate",
|
||||
"alfa_typeopportunity", "alfa_tipodeventa", "_ownerid_value", "_customerid_value",
|
||||
"_alfa_lineadenegocioid_value", "_campaignid_value", "estimatedvalue", "actualvalue",
|
||||
].join(",");
|
||||
|
||||
function mapCohorteRow(o) {
|
||||
const tipo = fv(o, "alfa_typeopportunity");
|
||||
const creada = o.createdon ? o.createdon.slice(0, 10) : null;
|
||||
const estado = o.statecode === 1 ? "Ganada" : o.statecode === 2 ? "Perdida" : "Abierta";
|
||||
const cierre = o.actualclosedate ? o.actualclosedate.slice(0, 10) : null;
|
||||
const hoy = new Date().toISOString().slice(0, 10);
|
||||
const diasEntre = (a, b) => (a && b ? Math.round((new Date(b) - new Date(a)) / 86400000) : null);
|
||||
return {
|
||||
id: o.opportunityid,
|
||||
name: o.name,
|
||||
owner: fv(o, "_ownerid_value"),
|
||||
cliente: fv(o, "_customerid_value"),
|
||||
creada,
|
||||
mesCohorte: creada ? creada.slice(0, 7) : null,
|
||||
estado,
|
||||
cierre,
|
||||
tipo,
|
||||
segmento: segmentoDe(tipo),
|
||||
origen: fv(o, "alfa_tipodeventa"),
|
||||
linea: fv(o, "_alfa_lineadenegocioid_value"),
|
||||
campaign: fv(o, "_campaignid_value"),
|
||||
est: o.estimatedvalue || 0,
|
||||
val: o.actualvalue || 0,
|
||||
diasACierre: estado !== "Abierta" ? diasEntre(creada, cierre) : null,
|
||||
diasAbierta: estado === "Abierta" ? diasEntre(creada, hoy) : null,
|
||||
};
|
||||
}
|
||||
|
||||
// scope: { email, locked }. mesesAtras: ventana de creación — el sitio HTML deja elegir el rango;
|
||||
// acá se fija a 6 meses para acotar el volumen de la consulta en vivo (createdon no tiene índice
|
||||
// de "top N recientes" propio, así que sin tope esto podría traer años de historial).
|
||||
export async function getCohorte(accessToken, scope, mesesAtras = 6) {
|
||||
const desde = new Date();
|
||||
desde.setMonth(desde.getMonth() - mesesAtras);
|
||||
desde.setDate(1);
|
||||
const filterDesde = desde.toISOString().slice(0, 10);
|
||||
|
||||
let filter = `createdon ge ${filterDesde}`;
|
||||
if (scope.emails?.length) {
|
||||
const ownerIds = await resolveOwnerIds(scope.emails, accessToken);
|
||||
if (!ownerIds.length) return [];
|
||||
filter += ` and ${ownerOrClause(ownerIds)}`;
|
||||
}
|
||||
const data = await dv(
|
||||
`opportunities?$select=${COHORTE_SELECT}&$filter=${encodeURIComponent(filter)}&$top=5000`,
|
||||
accessToken
|
||||
);
|
||||
return (data.value || []).map(mapCohorteRow);
|
||||
}
|
||||
|
||||
// roster: lista de nombres a incluir cuando no hay un solo propietario en `scope` (default
|
||||
// EJECUTIVOS_VENTA) — Renovaciones pasa EJECUTIVOS_RENOV (Ventas + SAC, ver CLAUDE.md) para no
|
||||
// perderse las actividades de SAC en el cruce "¿Ya se agendó algo?".
|
||||
export async function getActividades(accessToken, scope, roster = EJECUTIVOS_VENTA) {
|
||||
let ownerIds;
|
||||
if (scope.emails?.length) {
|
||||
ownerIds = await resolveOwnerIds(scope.emails, accessToken);
|
||||
} else {
|
||||
const users = await getSystemUsers(accessToken);
|
||||
ownerIds = users.filter((u) => roster.includes(u.name)).map((u) => u.id);
|
||||
}
|
||||
if (!ownerIds.length) return [];
|
||||
|
||||
const cutoff = new Date(Date.now() - ACTIVIDADES_DIAS_HISTORIA * 86400000).toISOString().slice(0, 10);
|
||||
const ownerFilterStr = `(${ownerIds.map((id) => `_ownerid_value eq ${id}`).join(" or ")})`;
|
||||
const filter = `(statecode eq 0 or scheduledend ge ${cutoff}) and ${ownerFilterStr}`;
|
||||
|
||||
const results = await Promise.all(
|
||||
ACTIVIDAD_ENTIDADES.map(async ({ entity, tipo, navProp, propioField, propioLabel }) => {
|
||||
// actualend/statuscode salieron del $select: se traían pero nada en la UI los lee — menos
|
||||
// columnas por fila, Dataverse arma la respuesta más rápido (3 consultas en paralelo con
|
||||
// $expand, la página más pesada de la app).
|
||||
const select = [
|
||||
"activityid", "subject", "scheduledstart", "scheduledend",
|
||||
"statecode", "_ownerid_value", "_regardingobjectid_value",
|
||||
"_alfa_objetivodeactividad_value", propioField,
|
||||
];
|
||||
const query =
|
||||
`${entity}?$select=${select.join(",")}` +
|
||||
`&$expand=${navProp}($select=opportunityid,name,estimatedvalue,alfa_typeopportunity,msdyn_forecastcategory,estimatedclosedate,_customerid_value)` +
|
||||
`&$filter=${encodeURIComponent(filter)}&$top=5000`;
|
||||
const data = await dv(query, accessToken);
|
||||
return (data.value || []).map((r) => mapActividadRow(r, tipo, navProp, propioField, propioLabel));
|
||||
})
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
4
app/loading.js
Normal file
4
app/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "./components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
4
app/nuevas/loading.js
Normal file
4
app/nuevas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
335
app/nuevas/page.js
Normal file
335
app/nuevas/page.js
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getCohorte, getMotivosCierre, getSystemUsers } from "../lib/queries";
|
||||
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import Panel from "../components/pipeline/Panel";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import CohMatriz from "../components/nuevas/CohMatriz";
|
||||
import MesesControl from "../components/nuevas/MesesControl";
|
||||
import FilterableRow from "../components/FilterableRow";
|
||||
import { DYN, money, money2 } from "../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const COH_DIMS = [
|
||||
{ k: "owner", lbl: "Ejecutivo" },
|
||||
{ k: "origen", lbl: "Origen" },
|
||||
{ k: "tipo", lbl: "Tipo de oportunidad" },
|
||||
{ k: "linea", lbl: "Línea de negocio" },
|
||||
{ k: "campaign", lbl: "Campaña" },
|
||||
];
|
||||
const COH_METRICAS = [
|
||||
{ k: "pct", lbl: "% Ganada", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Ganada").length / a.length) * 100) : null) },
|
||||
{ k: "pctP", lbl: "% Perdida", rgb: "178,58,46", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Perdida").length / a.length) * 100) : null) },
|
||||
{ k: "n", lbl: "Creadas", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}`), calc: (a) => a.length || null },
|
||||
{ k: "mrr", lbl: "MRR ganado", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : money(v)), calc: (a) => { const s = a.filter((o) => o.estado === "Ganada").reduce((x, o) => x + o.val, 0); return a.length ? s : null; } },
|
||||
];
|
||||
const DIM_LABELS = { owner: "Ejecutivo", origen: "Origen", tipo: "Tipo", linea: "Línea", campaign: "Campaña", mesCohorte: "Mes de creación", motivo: "Motivo de cierre", competidor: "Competidor" };
|
||||
|
||||
const MESLBL = {
|
||||
"01": "Ene", "02": "Feb", "03": "Mar", "04": "Abr", "05": "May", "06": "Jun",
|
||||
"07": "Jul", "08": "Ago", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dic",
|
||||
};
|
||||
const mesLbl = (m) => (m ? `${MESLBL[m.slice(5, 7)] || m.slice(5, 7)} ${m.slice(0, 4)}` : "—");
|
||||
const COH_TIPOS = {
|
||||
venta: { lbl: "Venta y expansión", tipos: ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling", "Plan de Cuenta"] },
|
||||
renov: { lbl: "Renovaciones", tipos: ["Contrato vencido", "Próximo a Vencer en 30/60/90"] },
|
||||
todas: { lbl: "Todas", tipos: null },
|
||||
};
|
||||
const ESTADOS = [
|
||||
{ k: "Ganada", color: "#2e8b57" },
|
||||
{ k: "Perdida", color: "var(--pierde)" },
|
||||
{ k: "Abierta", color: "#1e71b8" },
|
||||
];
|
||||
|
||||
function BarraCohorte({ mes, rows }) {
|
||||
const tot = rows.length || 1;
|
||||
return (
|
||||
<FilterableRow pairs={[["mesCohorte", mes]]} className="row" style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }} title={`Ver solo ${mesLbl(mes)}`}>
|
||||
<span style={{ width: 70, fontSize: 12 }}>{mesLbl(mes)}</span>
|
||||
<div style={{ flex: 1, display: "flex", height: 22, borderRadius: 4, overflow: "hidden", background: "#eef2f5" }}>
|
||||
{ESTADOS.map(({ k, color }) => {
|
||||
const n = rows.filter((o) => o.estado === k).length;
|
||||
if (!n) return null;
|
||||
const pct = (n / tot) * 100;
|
||||
return (
|
||||
<div
|
||||
key={k}
|
||||
title={`${k}: ${n} de ${rows.length} (${Math.round(pct)}%)`}
|
||||
style={{
|
||||
width: `${pct}%`, background: color, display: "flex", alignItems: "center",
|
||||
justifyContent: "center", color: "#fff", fontSize: 11, fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
{pct > 11 ? `${n} (${Math.round(pct)}%)` : ""}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<span style={{ width: 36, textAlign: "right", fontSize: 12 }}>{rows.length}</span>
|
||||
</FilterableRow>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function NuevasPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner, tipos: tiposParam } = sp;
|
||||
const mesesSel = typeof sp.meses === "string" && sp.meses ? sp.meses.split(",") : null;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const cohTipos = COH_TIPOS[tiposParam] ? tiposParam : "venta";
|
||||
const filt = parseFiltParam(sp.f);
|
||||
const cohd = COH_DIMS.some((d) => d.k === sp.cohd) ? sp.cohd : "owner";
|
||||
const cohm = COH_METRICAS.some((m) => m.k === sp.cohm) ? sp.cohm : "pct";
|
||||
|
||||
let arrAll, allUsers;
|
||||
try {
|
||||
[arrAll, allUsers] = await Promise.all([
|
||||
getCohorte(session.accessToken, scope),
|
||||
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||
const tiposFiltro = COH_TIPOS[cohTipos].tipos;
|
||||
const arrTipo = tiposFiltro ? arrAll.filter((o) => tiposFiltro.includes(o.tipo)) : arrAll;
|
||||
const mesesDisp = [...new Set(arrTipo.map((o) => o.mesCohorte).filter(Boolean))].sort();
|
||||
const mesesActivos = mesesSel ? mesesDisp.filter((m) => mesesSel.includes(m)) : mesesDisp;
|
||||
const mesesEfectivos = mesesActivos.length ? mesesActivos : mesesDisp;
|
||||
const arrMes = arrTipo.filter((o) => mesesEfectivos.includes(o.mesCohorte));
|
||||
|
||||
// Motivo y competidor de cierre solo existen para las perdidas (opportunityclose).
|
||||
let arrEnr = arrMes;
|
||||
try {
|
||||
const perdidasIds = arrMes.filter((o) => o.estado === "Perdida").map((o) => o.id);
|
||||
const motivos = await getMotivosCierre(perdidasIds, session.accessToken);
|
||||
arrEnr = arrMes.map((o) =>
|
||||
o.estado === "Perdida"
|
||||
? { ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor || "Sin registrar" }
|
||||
: o
|
||||
);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const arr = applyFilt(arrEnr, filt);
|
||||
|
||||
const linkFor = (t) => {
|
||||
const params = new URLSearchParams();
|
||||
if (owner) params.set("owner", owner);
|
||||
if (sp.meses) params.set("meses", sp.meses);
|
||||
params.set("tipos", t);
|
||||
return `/nuevas?${params.toString()}`;
|
||||
};
|
||||
|
||||
const meses = [...new Set(arr.map((o) => o.mesCohorte).filter(Boolean))].sort();
|
||||
const g = arr.filter((o) => o.estado === "Ganada");
|
||||
const p = arr.filter((o) => o.estado === "Perdida");
|
||||
const ab = arr.filter((o) => o.estado === "Abierta");
|
||||
const cerr = g.length + p.length;
|
||||
const pct = (x) => (arr.length ? Math.round((x / arr.length) * 100) : 0);
|
||||
const mrrG = g.reduce((a, o) => a + o.val, 0);
|
||||
|
||||
const cohAgg = (key) => agg(arr, key, (o) => (o.estado === "Ganada" ? o.val : 0));
|
||||
|
||||
const cerradas = arr.filter((o) => o.diasACierre != null);
|
||||
const tramos = [
|
||||
{ lbl: "Mismo día", max: 0 }, { lbl: "1 a 7 días", max: 7 }, { lbl: "8 a 30 días", max: 30 },
|
||||
{ lbl: "31 a 90 días", max: 90 }, { lbl: "Más de 90 días", max: Infinity },
|
||||
];
|
||||
let prev = -1;
|
||||
const latRows = tramos.map((t) => {
|
||||
const n = cerradas.filter((o) => o.diasACierre > prev && o.diasACierre <= t.max).length;
|
||||
prev = t.max;
|
||||
return { k: t.lbl, n };
|
||||
});
|
||||
const maxLat = Math.max(...latRows.map((r) => r.n), 1);
|
||||
const medianaDias = (() => {
|
||||
const a = cerradas.map((o) => o.diasACierre).sort((x, y) => x - y);
|
||||
return a.length ? a[Math.floor(a.length / 2)] : 0;
|
||||
})();
|
||||
const viejas = arr.filter((o) => o.diasAbierta != null && o.diasAbierta > 90);
|
||||
|
||||
const detalle = [...arr].sort((a, b) => (b.estado === "Ganada" ? b.val : b.est) - (a.estado === "Ganada" ? a.val : a.est)).slice(0, 300);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Cohorte de Oportunidades</h2>
|
||||
<div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
|
||||
<MesesControl opciones={mesesDisp.map((m) => ({ k: m, lbl: mesLbl(m) }))} seleccion={mesesEfectivos} />
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||
{Object.entries(COH_TIPOS).map(([k, v]) => (
|
||||
<a key={k} href={linkFor(k)}>
|
||||
<button className={cohTipos === k ? "on" : ""} type="button">{v.lbl}</button>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{arr.length === 0 ? (
|
||||
<p>No hay oportunidades creadas en el período y alcance seleccionados.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{arr.length}</span><span className="l">Oportunidades creadas (cohorte)</span></div>
|
||||
<div className="kpi"><span className="n" style={{ color: "var(--gana)" }}>{g.length}</span><span className="l">Hoy Ganadas · {pct(g.length)}%</span></div>
|
||||
<div className="kpi"><span className="n pierde">{p.length}</span><span className="l">Hoy Perdidas · {pct(p.length)}%</span></div>
|
||||
<div className="kpi"><span className="n">{ab.length}</span><span className="l">Todavía Abiertas · {pct(ab.length)}%</span></div>
|
||||
<div className="kpi"><span className="n">{cerr ? `${Math.round((g.length / cerr) * 100)}%` : "n/d"}</span><span className="l">Efectividad (gana ÷ resueltas)</span></div>
|
||||
<div className="kpi"><span className="n">{money(mrrG)}</span><span className="l">MRR ganado por esta cohorte</span></div>
|
||||
</div>
|
||||
|
||||
<div className="callout info">
|
||||
Está página analiza el <b>"Cohorte"</b>, es decir el comportamiento de las oportunidades según su{" "}
|
||||
<b>"Fecha de Creación"</b>. Ayuda a entender que pasó con las oportunidades que se crearon cada mes.
|
||||
<br /><br />
|
||||
De las <b>{arr.length}</b> oportunidades creadas en los últimos 6 meses, hoy {g.length} están ganadas, {p.length}{" "}
|
||||
perdidas y {ab.length} siguen abiertas. Las cohortes recientes tienen más abiertas solo porque son
|
||||
jóvenes — mirá "% resuelto" y la latencia antes de comparar. Plan de Cuenta y los leads de
|
||||
formularios/bots convierten poco <b>por diseño</b> (los genera telemarketing en volumen); el error a
|
||||
buscar ahí es lentitud para calificar, no baja conversión.
|
||||
</div>
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
|
||||
<div className="panel">
|
||||
<h3>Desenlace por cohorte de creación (estado de hoy)</h3>
|
||||
<p className="hint">Cada barra es el 100% de lo creado ese mes</p>
|
||||
{meses.map((m) => <BarraCohorte key={m} mes={m} rows={arr.filter((o) => o.mesCohorte === m)} />)}
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 18 }}>
|
||||
<CohMatriz arr={arr} meses={meses} dims={COH_DIMS} metricas={COH_METRICAS} activeDimKey={cohd} activeMetKey={cohm} mesLbl={mesLbl} />
|
||||
</div>
|
||||
|
||||
<div className="grid2" style={{ marginTop: 18 }}>
|
||||
<div className="panel">
|
||||
<h3>Latencia de decisión</h3>
|
||||
<p className="hint">
|
||||
Días entre crear y cerrar, de las {cerradas.length} ya resueltas
|
||||
</p>
|
||||
{latRows.map((r) => (
|
||||
<div className="row static" key={r.k}>
|
||||
<div className="bl"><span className="nm">{r.k}</span></div>
|
||||
<div className="bar-cell"><div className="bar-fill" style={{ width: `${(r.n / maxLat) * 100}%` }} /></div>
|
||||
<span className="v">{r.n}</span>
|
||||
<span className="c">{cerradas.length ? Math.round((r.n / cerradas.length) * 100) : 0}%</span>
|
||||
</div>
|
||||
))}
|
||||
<p className="hint" style={{ marginTop: 10 }}>
|
||||
Mediana: <b>{medianaDias} días</b> para resolver.
|
||||
{viejas.length > 0 && (
|
||||
<> Y hay <b>{viejas.length}</b> todavía abiertas con más de 90 días de vida ({money(viejas.reduce((a, o) => a + o.est, 0))} estimado).</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<Panel title="Por Origen de la Oportunidad" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("origen")} top={8} dimKey="origen" />
|
||||
</div>
|
||||
|
||||
<div className="grid2" style={{ marginTop: 18 }}>
|
||||
<Panel title="Por Tipo de Oportunidad" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("tipo")} dimKey="tipo" />
|
||||
<Panel title="Por Ejecutivo" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("owner")} dimKey="owner" />
|
||||
</div>
|
||||
<div className="grid2" style={{ marginTop: 18 }}>
|
||||
<Panel title="Por Línea de Negocio" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("linea")} dimKey="linea" />
|
||||
<Panel title="Por Campaña de Origen" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("campaign")} top={7} dimKey="campaign" />
|
||||
</div>
|
||||
|
||||
<div className="grid2" style={{ marginTop: 18 }}>
|
||||
<Panel title="Motivo de cierre" hint="Solo perdidas de la cohorte · barra = cantidad · monto = MRR estimado" rows={agg(p, "motivo", (o) => o.est)} top={8} dimKey="motivo" />
|
||||
<Panel title="Competidor" hint="Solo perdidas de la cohorte · barra = cantidad · monto = MRR estimado" rows={agg(p.filter((o) => o.competidor && o.competidor !== "Ninguno"), "competidor", (o) => o.est)} top={8} dimKey="competidor" />
|
||||
</div>
|
||||
|
||||
<div className="tw fit" style={{ marginTop: 18 }}>
|
||||
<div className="tw-title">
|
||||
<h3>Cohortes en números</h3>
|
||||
|
||||
</div>
|
||||
<div className="ts" style={{ maxHeight: "none" }}>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cohorte</th><th className="num">Creadas</th><th className="num">Ganadas</th><th className="num">% Gana</th>
|
||||
<th className="num">Perdidas</th><th className="num">% Pierde</th><th className="num">Abiertas</th>
|
||||
<th className="num">% Resuelto</th><th className="num">MRR ganado</th><th className="num">Edad prom.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{meses.map((m) => {
|
||||
const c = arr.filter((o) => o.mesCohorte === m);
|
||||
const cg = c.filter((o) => o.estado === "Ganada"), cp = c.filter((o) => o.estado === "Perdida"), ca = c.filter((o) => o.estado === "Abierta");
|
||||
const cpct = (x) => (c.length ? `${Math.round((x / c.length) * 100)}%` : "—");
|
||||
const cerrC = cg.length + cp.length;
|
||||
const edad = c.length ? Math.round(c.reduce((s, o) => s + (o.diasACierre ?? o.diasAbierta ?? 0), 0) / c.length) : 0;
|
||||
return (
|
||||
<FilterableRow as="tr" pairs={[["mesCohorte", m]]} key={m} title={`Ver solo ${mesLbl(m)}`}>
|
||||
<td><b>{mesLbl(m)}</b></td>
|
||||
<td className="num">{c.length}</td>
|
||||
<td className="num" style={{ color: "var(--gana)", fontWeight: 700 }}>{cg.length}</td>
|
||||
<td className="num">{cpct(cg.length)}</td>
|
||||
<td className="num" style={{ color: "var(--pierde)", fontWeight: 700 }}>{cp.length}</td>
|
||||
<td className="num">{cpct(cp.length)}</td>
|
||||
<td className="num">{ca.length}</td>
|
||||
<td className="num">{c.length ? `${Math.round((cerrC / c.length) * 100)}%` : "—"}</td>
|
||||
<td className="num">{money(cg.reduce((s, o) => s + o.val, 0))}</td>
|
||||
<td className="num">{edad} d</td>
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ paddingBottom: 6, marginTop: 18 }}>
|
||||
<h3>Detalle de la cohorte</h3>
|
||||
<p className="hint">Las 300 de mayor monto</p>
|
||||
</div>
|
||||
<div className="tw">
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente / Oportunidad</th><th>Estado</th><th>Ejecutivo</th><th>Tipo</th><th>Origen</th>
|
||||
<th className="num">MRR</th><th>Creada</th><th className="num">Días</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{detalle.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td className="dual-cel">
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener" title={o.name}>{o.name}</a>
|
||||
<span className="sub">{o.cliente || "—"}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span className={o.estado === "Ganada" ? "gana" : o.estado === "Perdida" ? "pierde" : ""}>{o.estado}</span>
|
||||
</td>
|
||||
<td className="elip">{o.owner}</td>
|
||||
<td className="elip" title={o.tipo || ""}>{o.tipo || "—"}</td>
|
||||
<td className="elip" title={o.origen || ""}>{o.origen || "—"}</td>
|
||||
<td className="num">{money2(o.estado === "Ganada" ? o.val : o.est)}</td>
|
||||
<td>{o.creada || "—"}</td>
|
||||
<td className="num" title={o.diasACierre != null ? "Días que tardó en cerrarse" : "Días que lleva abierta"}>
|
||||
{o.diasACierre != null ? o.diasACierre : o.diasAbierta != null ? `${o.diasAbierta}…` : "—"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
39
app/page.js
Normal file
39
app/page.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { auth } from "./lib/auth";
|
||||
import { ownerFilter } from "./lib/authz";
|
||||
import { getActividades, getSystemUsers } from "./lib/queries";
|
||||
import { EJECUTIVOS_VENTA } from "./lib/derive";
|
||||
import LoginPrompt from "./components/LoginPrompt";
|
||||
import OwnerControl from "./components/OwnerControl";
|
||||
import ErrorNotice from "./components/ErrorNotice";
|
||||
import AgendaClient from "./components/agenda/AgendaClient";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function Home({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const { owner } = await searchParams;
|
||||
const scope = ownerFilter(session, owner);
|
||||
|
||||
let actividades, allUsers;
|
||||
try {
|
||||
[actividades, allUsers] = await Promise.all([
|
||||
getActividades(session.accessToken, scope),
|
||||
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Agenda</h2>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
<AgendaClient actividades={actividades} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/perdemos/loading.js
Normal file
4
app/perdemos/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
156
app/perdemos/page.js
Normal file
156
app/perdemos/page.js
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getClosedRange, getMotivosCierre, getSystemUsers, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { agg, PROPIETARIOS_VENTA } from "../lib/derive";
|
||||
import { PERIODOS, periodoActivo, rangoDePeriodo } from "../lib/periodos";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import SegTabs from "../components/SegTabs";
|
||||
import Panel from "../components/pipeline/Panel";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import { DYN, money, money2 } from "../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DIM_LABELS = { motivo: "Motivo", competidor: "Competidor", servicio: "Servicio", origen: "Origen", owner: "Ejecutivo" };
|
||||
|
||||
export default async function PerdemosPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const periodo = periodoActivo(sp.periodo);
|
||||
const { from, to, lbl: periodoLbl } = rangoDePeriodo(periodo);
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
let lostAll, allUsers;
|
||||
try {
|
||||
[lostAll, allUsers] = await Promise.all([
|
||||
getClosedRange(session.accessToken, scope, 2, from, to, undefined, VENTA_TYPE_FILTER),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
const motivos = await getMotivosCierre(lostAll.map((o) => o.id), session.accessToken);
|
||||
lostAll = lostAll.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor }));
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
|
||||
const lost = applyFilt(lostAll, filt);
|
||||
|
||||
const mrrPerdido = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||
const clientesNuevos = lost.filter((o) => o.segmento === "Clientes Nuevos").length;
|
||||
const carteraActiva = lost.filter((o) => o.segmento === "Cartera Activa").length;
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Por qué Perdemos</h2>
|
||||
<OwnerControl
|
||||
owners={owners}
|
||||
current={scope.locked ? [session.email] : scope.emails}
|
||||
locked={scope.locked}
|
||||
lockedLabel={session.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={PERIODOS} activeKey={periodo} paramName="periodo" />
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<span className="n pierde">{lost.length}</span>
|
||||
<span className="l">Oportunidades perdidas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n pierde">{money(mrrPerdido)}</span>
|
||||
<span className="l">MRR estimado perdido</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{clientesNuevos}</span>
|
||||
<span className="l">Clientes Nuevos</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{carteraActiva}</span>
|
||||
<span className="l">Cartera Activa</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="hint">
|
||||
Mostrando {periodoLbl}. Sin seguimiento en el CRM no significa sin seguimiento: WhatsApp no está en Dynamics.
|
||||
</p>
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="grid2">
|
||||
<Panel
|
||||
title="Motivo de cierre"
|
||||
hint='Fuente: Cierre de oportunidad en Dynamics · "Sin registrar" = ningún motivo (Alfa ni estándar) quedó guardado'
|
||||
rows={agg(lost, "motivo", (o) => o.est)}
|
||||
cls="pierde"
|
||||
dimKey="motivo"
|
||||
/>
|
||||
<Panel
|
||||
title="Competidor"
|
||||
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Ninguno"), "competidor", (o) => o.est)}
|
||||
cls="pierde"
|
||||
dimKey="competidor"
|
||||
/>
|
||||
<Panel title="Servicio / Producto" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" dimKey="servicio" />
|
||||
<Panel title="Origen de la oportunidad" rows={agg(lost, "origen", (o) => o.est)} cls="pierde" dimKey="origen" />
|
||||
<Panel title="Perdidas por ejecutivo" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" dimKey="owner" />
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Detalle de oportunidades perdidas</h3>
|
||||
</div>
|
||||
{lost.length === 0 ? (
|
||||
<p>No hay oportunidades perdidas en este período para este filtro.</p>
|
||||
) : (
|
||||
<div className="tw">
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Seg.</th>
|
||||
<th>Motivo de cierre</th>
|
||||
<th>Línea de Negocio</th>
|
||||
<th>Competidor</th>
|
||||
{!scope.locked && <th>Ejecutivo</th>}
|
||||
<th className="num">MRR est.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td>
|
||||
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||
{o.name}
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||
</span>
|
||||
</td>
|
||||
<td>{o.motivo}</td>
|
||||
<td>{o.linea || "—"}</td>
|
||||
<td>{o.competidor || "—"}</td>
|
||||
{!scope.locked && <td>{o.owner}</td>}
|
||||
<td className="num">{o.est ? money2(o.est) : "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
app/plan/actions.js
Normal file
44
app/plan/actions.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "../lib/auth";
|
||||
import { getActividades, getSystemUsers, resolveOwnerId } from "../lib/queries";
|
||||
import { armarPlan, crearFoto, hoyManagua } from "../lib/plan";
|
||||
import { guardarPlanCerrado } from "../lib/planCerrado";
|
||||
|
||||
// «Marcar plan como listo»: guarda una foto del plan del ejecutivo para ese día (Plan del Día,
|
||||
// etapa 3). La foto se arma AQUÍ, en el servidor, a partir de Dynamics — nunca se confía en lo que
|
||||
// mande el navegador. El vendedor solo puede marcar su propio plan; el administrador, el de cualquier
|
||||
// ejecutivo. Solo se puede marcar hoy o días futuros: una foto tomada después del hecho no sirve
|
||||
// para el coaching.
|
||||
export async function marcarPlanListo(fecha, ownerEmail) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión para marcar el plan." };
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(fecha || "")) return { ok: false, error: "La fecha del plan no es válida." };
|
||||
const hoy = hoyManagua();
|
||||
if (fecha < hoy) return { ok: false, error: "El plan de un día pasado ya no se puede marcar como listo." };
|
||||
|
||||
const email = session.isAdmin ? String(ownerEmail || "").toLowerCase() : session.email;
|
||||
if (!email) return { ok: false, error: "Elige un solo ejecutivo para marcar su plan." };
|
||||
|
||||
try {
|
||||
const ownerId = await resolveOwnerId(email, session.accessToken);
|
||||
if (!ownerId) return { ok: false, error: "No encontré a ese ejecutivo en Dynamics." };
|
||||
const [actividades, users] = await Promise.all([
|
||||
getActividades(session.accessToken, { emails: [email], locked: !session.isAdmin }),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
const foto = crearFoto(armarPlan(actividades, fecha, hoy), fecha);
|
||||
if (!foto.nActs) return { ok: false, error: "Ese día no hay actividades agendadas que marcar." };
|
||||
const version = guardarPlanCerrado({
|
||||
fecha,
|
||||
ownerId,
|
||||
ownerName: users.find((u) => u.id === ownerId)?.name || email,
|
||||
marcadoPor: session.email,
|
||||
snapshot: foto,
|
||||
});
|
||||
revalidatePath("/plan");
|
||||
return { ok: true, version };
|
||||
} catch {
|
||||
return { ok: false, error: "No se pudo guardar el plan. Intenta de nuevo." };
|
||||
}
|
||||
}
|
||||
287
app/plan/page.js
Normal file
287
app/plan/page.js
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
import { Suspense } from "react";
|
||||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import {
|
||||
getActividades, getClosedRange, getSystemUsers, getOportunidadesSemana, resolveOwnerId, VENTA_TYPE_FILTER, REN_TYPE_FILTER,
|
||||
} from "../lib/queries";
|
||||
import { getVersionesPlan, getPlanCerrado, getPlanesListosDelDia } from "../lib/planCerrado";
|
||||
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import { AGENDADOR } from "../lib/agendador";
|
||||
import { money } from "../lib/constants";
|
||||
import {
|
||||
armarPlan, sinActividadAgendada, resumenEquipo, compararConFoto, hoyManagua, addDays, semanaDe, SECCIONES,
|
||||
} from "../lib/plan";
|
||||
import PlanListoBoton from "../components/plan/PlanListoBoton";
|
||||
import PlanSeccion from "../components/plan/PlanSeccion";
|
||||
import MrrSegmentos from "../components/plan/MrrSegmentos";
|
||||
import SinActividadPanel from "../components/plan/SinActividadPanel";
|
||||
import PlanVsReal from "../components/plan/PlanVsReal";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import PlanControles from "../components/plan/PlanControles";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
||||
const suma = (rows) => rows.reduce((t, o) => t + (o.actual || 0), 0);
|
||||
|
||||
// Momento en que se marcó un plan (se guarda en UTC), en hora de Nicaragua: «26/10 8:41 a. m.».
|
||||
function fmtMarca(iso) {
|
||||
const d = new Date(iso);
|
||||
const dia = new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", day: "2-digit", month: "2-digit" }).format(d);
|
||||
const hora = new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", hour: "numeric", minute: "2-digit" }).format(d);
|
||||
return `${dia} ${hora}`;
|
||||
}
|
||||
|
||||
// Casos y cuentas no tienen valor estimado: si la celda no suma valor, solo se muestra la cantidad.
|
||||
const celda = (c) => (c.n ? (c.valor ? `${c.n} · ${money(c.valor)}` : `${c.n}`) : "—");
|
||||
|
||||
function ResumenEquipo({ resumen, fecha, ventasTotal, renovTotal, listoPorNombre }) {
|
||||
const { lineas, total, otros } = resumen;
|
||||
const nListos = lineas.filter((l) => listoPorNombre[l.nombre]).length;
|
||||
return (
|
||||
<section className="plan-equipo">
|
||||
<h1 className="plan-titulo plan-titulo-eq">PLAN DEL DÍA — RESUMEN DEL EQUIPO</h1>
|
||||
<div className="plan-meta">
|
||||
<span><strong>Fecha:</strong> {fechaTxt(fecha)}</span>
|
||||
</div>
|
||||
<div className="kpis plan-kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{money(ventasTotal)}</span>
|
||||
<span className="l">Ventas logradas del mes (al {fechaTxt(fecha)})</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(renovTotal)}</span>
|
||||
<span className="l">Renovaciones logradas del mes (al {fechaTxt(fecha)})</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{total.actHechas} de {total.actTotal}</span>
|
||||
<span className="l">Actividades del día completadas</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ts">
|
||||
<table className="plan-eq-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th>
|
||||
{SECCIONES.map((s) => <th key={s.key} className="num">{s.titulo}</th>)}
|
||||
<th className="num">Completadas</th>
|
||||
<th className="num">Plan listo</th>
|
||||
<th className="num">Ventas del mes</th>
|
||||
<th className="num">Renov. del mes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{lineas.map((l) => (
|
||||
<tr key={l.nombre}>
|
||||
<td>{l.nombre}</td>
|
||||
{SECCIONES.map((s) => <td key={s.key} className="num">{celda(l.secs[s.key])}</td>)}
|
||||
<td className="num">{l.actTotal ? `${l.actHechas} de ${l.actTotal}` : "—"}</td>
|
||||
<td className="num">{listoPorNombre[l.nombre] ? `✓ ${listoPorNombre[l.nombre]}` : "—"}</td>
|
||||
<td className="num">{money(l.ventasMes)}</td>
|
||||
<td className="num">{money(l.renovMes)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{otros && (
|
||||
<tr className="plan-otros">
|
||||
<td>Otros propietarios</td>
|
||||
{SECCIONES.map((s) => <td key={s.key} className="num">—</td>)}
|
||||
<td className="num">—</td>
|
||||
<td className="num">—</td>
|
||||
<td className="num">{money(otros.ventasMes)}</td>
|
||||
<td className="num">{money(otros.renovMes)}</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td><strong>Total equipo</strong></td>
|
||||
{SECCIONES.map((s) => <td key={s.key} className="num"><strong>{celda(total.secs[s.key])}</strong></td>)}
|
||||
<td className="num"><strong>{total.actTotal ? `${total.actHechas} de ${total.actTotal}` : "—"}</strong></td>
|
||||
<td className="num"><strong>{nListos} de {lineas.length}</strong></td>
|
||||
<td className="num"><strong>{money(total.ventasMes)}</strong></td>
|
||||
<td className="num"><strong>{money(total.renovMes)}</strong></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<p className="hint plan-eq-nota">
|
||||
Cada celda: oportunidades, casos o cuentas con actividad agendada ese día · valor estimado. Ventas y renovaciones del mes
|
||||
suman lo ganado por cada ejecutivo hasta el {fechaTxt(fecha)}.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
export default async function PlanDelDia({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const scope = ownerFilter(session, sp.owner, { asistente: true });
|
||||
const hoy = hoyManagua();
|
||||
const fecha = /^\d{4}-\d{2}-\d{2}$/.test(sp.fecha || "") ? sp.fecha : hoy;
|
||||
const desdeMes = `${fecha.slice(0, 7)}-01`;
|
||||
const hastaDia = addDays(fecha, 1);
|
||||
const { lunes, domingo } = semanaDe(fecha);
|
||||
|
||||
let actividades, ventas, renovaciones, allUsers, oppsSemana;
|
||||
try {
|
||||
[actividades, ventas, renovaciones, allUsers, oppsSemana] = await Promise.all([
|
||||
getActividades(session.accessToken, scope),
|
||||
getClosedRange(session.accessToken, scope, 1, desdeMes, hastaDia, undefined, VENTA_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, scope, 1, desdeMes, hastaDia, undefined, REN_TYPE_FILTER),
|
||||
session.isAdmin || scope.asistente ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
getOportunidadesSemana(session.accessToken, scope, lunes, domingo),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
// La asistente solo ve a los ejecutivos del piloto (ver ownerFilter).
|
||||
const owners = allUsers
|
||||
.filter((u) => EJECUTIVOS_VENTA.includes(u.name))
|
||||
.filter((u) => !scope.asistente || AGENDADOR.piloto.includes(u.email));
|
||||
const plan = armarPlan(actividades, fecha, hoy);
|
||||
|
||||
// "Todos" (sin propietario elegido) = el equipo de ventas curado, como en el resto del informe.
|
||||
const sinActividad = sinActividadAgendada(
|
||||
scope.emails?.length ? oppsSemana : oppsSemana.filter((o) => EJECUTIVOS_VENTA.includes(o.owner)),
|
||||
actividades,
|
||||
fecha
|
||||
);
|
||||
|
||||
const quien = scope.locked
|
||||
? session.email
|
||||
: scope.emails.length === 1
|
||||
? owners.find((o) => o.email === scope.emails[0])?.name || scope.emails[0]
|
||||
: scope.emails.length
|
||||
? `${scope.emails.length} ejecutivos`
|
||||
: "Equipo";
|
||||
const tituloPdf = `Plan del día – ${quien} – ${fecha}`;
|
||||
|
||||
// Resumen del equipo: solo para el administrador cuando ve a más de un ejecutivo.
|
||||
const verEquipo = !scope.locked && scope.emails.length !== 1 && owners.length > 0;
|
||||
const nombresEquipo = owners
|
||||
.filter((o) => !scope.emails.length || scope.emails.includes(o.email))
|
||||
.map((o) => o.name);
|
||||
const resumen = verEquipo ? resumenEquipo(plan, nombresEquipo, ventas, renovaciones) : null;
|
||||
|
||||
// Plan cerrado (etapa 3): solo cuando se ve el plan de UN ejecutivo (el vendedor, o el
|
||||
// administrador con un solo propietario elegido). La foto se identifica por systemuserid.
|
||||
const unicoEmail = scope.locked ? session.email : scope.emails.length === 1 ? scope.emails[0] : null;
|
||||
let unicoId = null;
|
||||
let unicoNombre = null;
|
||||
let versiones = [];
|
||||
let foto = null;
|
||||
let comparacion = null;
|
||||
if (unicoEmail) {
|
||||
const u = owners.find((o) => o.email === unicoEmail);
|
||||
unicoId = u?.id || (await resolveOwnerId(unicoEmail, session.accessToken));
|
||||
unicoNombre = u?.name || quien;
|
||||
if (unicoId) {
|
||||
versiones = getVersionesPlan(fecha, unicoId);
|
||||
const pedida = Number(sp.version) || undefined;
|
||||
foto = getPlanCerrado(fecha, unicoId, pedida) || (pedida ? getPlanCerrado(fecha, unicoId) : null);
|
||||
if (foto) comparacion = compararConFoto(foto.snapshot, actividades, plan, hoy);
|
||||
}
|
||||
}
|
||||
const puedeMarcar = Boolean(unicoId) && fecha >= hoy;
|
||||
const ultimaVersion = versiones.length ? versiones[versiones.length - 1] : null;
|
||||
// Resumen del equipo: quién ya marcó su plan ese día (por nombre de ejecutivo).
|
||||
const listos = verEquipo ? getPlanesListosDelDia(fecha) : {};
|
||||
const listoPorNombre = {};
|
||||
owners.forEach((o) => {
|
||||
if (listos[o.id]) listoPorNombre[o.name] = fmtMarca(listos[o.id].marcado_en).split(" ").slice(1).join(" ");
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Plan del Día</h2>
|
||||
<div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
|
||||
<Suspense fallback={null}>
|
||||
<PlanControles
|
||||
fecha={fecha}
|
||||
hoy={hoy}
|
||||
tituloPdf={tituloPdf}
|
||||
tituloPdfEquipo={`Plan del día – Resumen del equipo – ${fecha}`}
|
||||
conEquipo={verEquipo}
|
||||
/>
|
||||
</Suspense>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{unicoId && (
|
||||
<PlanListoBoton
|
||||
fecha={fecha}
|
||||
ownerEmail={unicoEmail}
|
||||
nombre={unicoNombre}
|
||||
version={ultimaVersion?.version || null}
|
||||
marca={ultimaVersion ? fmtMarca(ultimaVersion.marcado_en) : ""}
|
||||
puedeMarcar={puedeMarcar}
|
||||
/>
|
||||
)}
|
||||
|
||||
{resumen && (
|
||||
<ResumenEquipo
|
||||
resumen={resumen}
|
||||
fecha={fecha}
|
||||
ventasTotal={suma(ventas)}
|
||||
renovTotal={suma(renovaciones)}
|
||||
listoPorNombre={listoPorNombre}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="plan-doc plan-detalle">
|
||||
<h1 className="plan-titulo">PLAN DE ACTIVIDADES DEL DÍA</h1>
|
||||
<div className="plan-meta">
|
||||
<span><strong>Fecha:</strong> {fechaTxt(fecha)}</span>
|
||||
<span><strong>Ejecutivo:</strong> {quien}</span>
|
||||
{ultimaVersion && <span><strong>Plan listo:</strong> {fmtMarca(ultimaVersion.marcado_en)}</span>}
|
||||
</div>
|
||||
|
||||
<div className="kpis plan-kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{money(suma(ventas))}</span>
|
||||
<span className="l">Ventas logradas del mes (al {fechaTxt(fecha)})</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(suma(renovaciones))}</span>
|
||||
<span className="l">Renovaciones logradas del mes (al {fechaTxt(fecha)})</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{plan.resumen.actHechas} de {plan.resumen.actTotal}</span>
|
||||
<span className="l">Actividades del día completadas</span>
|
||||
</div>
|
||||
<MrrSegmentos secciones={plan.secciones} nota="oportunidades con actividad este día" />
|
||||
</div>
|
||||
|
||||
{plan.secciones.map((s) => (
|
||||
<PlanSeccion key={s.key} seccion={s} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
{foto && comparacion && (
|
||||
<PlanVsReal
|
||||
foto={foto}
|
||||
versiones={versiones}
|
||||
cmp={comparacion}
|
||||
nombre={unicoNombre}
|
||||
marca={fmtMarca(foto.marcado_en)}
|
||||
hrefVersion={(v) => {
|
||||
const p = new URLSearchParams();
|
||||
if (sp.owner) p.set("owner", sp.owner);
|
||||
if (sp.fecha) p.set("fecha", sp.fecha);
|
||||
p.set("version", String(v));
|
||||
return `/plan?${p.toString()}`;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<SinActividadPanel filas={sinActividad} titulo="Oportunidades sin actividad agendada este día" hint={`Cierre estimado entre el ${fechaTxt(lunes)} y el ${fechaTxt(domingo)} (semana de la fecha elegida) · solo en pantalla, no va en el PDF`} vacio="Todas las oportunidades con cierre esta semana tienen una actividad agendada este día." />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/prevision/loading.js
Normal file
4
app/prevision/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
438
app/prevision/page.js
Normal file
438
app/prevision/page.js
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getPipeline, getSystemUsers, getActividades, getStageDurations, getClosedRange, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { agg, aggOrd, PLAN_ORDER, esPrioridadAlta, PRIORIDAD_COLOR, EJECUTIVOS_VENTA, hayClasif, decorarActividadVentana, ACTAGENDADA_ORDEN, pipeVelFor } from "../lib/derive";
|
||||
import { PERIODOS_PREVISION, periodoPrevisionActivo, rangoDePeriodoPrevision, rangoDePeriodo } from "../lib/periodos";
|
||||
import { getMetaGlobal, getMetas } from "../lib/metas";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import Panel from "../components/pipeline/Panel";
|
||||
import MatrizCalidad from "../components/pipeline/MatrizCalidad";
|
||||
import ExecMatrix from "../components/pipeline/ExecMatrix";
|
||||
import VelPanel from "../components/pipeline/VelPanel";
|
||||
import SegTabs from "../components/SegTabs";
|
||||
import FilterableRow from "../components/FilterableRow";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import ReportModal from "../components/ReportModal";
|
||||
import PanelesPrevision from "../components/pipeline/PanelesPrevision";
|
||||
import TablaPrevision from "../components/pipeline/TablaPrevision";
|
||||
import AyudaPrevision from "../components/pipeline/AyudaPrevision";
|
||||
import AccionTable from "../components/pipeline/AccionTable";
|
||||
import { money } from "../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
|
||||
const MESLBL_CAP = {
|
||||
"01": "Enero", "02": "Febrero", "03": "Marzo", "04": "Abril", "05": "Mayo", "06": "Junio",
|
||||
"07": "Julio", "08": "Agosto", "09": "Septiembre", "10": "Octubre", "11": "Noviembre", "12": "Diciembre",
|
||||
};
|
||||
function mesSiguiente(m) {
|
||||
const [y, mm] = m.split("-").map(Number);
|
||||
const d = new Date(y, mm, 1);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const IND_TABS = [
|
||||
{ k: "owner", lbl: "Ejecutivo" },
|
||||
{ k: "tipo", lbl: "Tipo" },
|
||||
{ k: "origen", lbl: "Origen" },
|
||||
{ k: "vel", lbl: "Velocidad" },
|
||||
];
|
||||
const IND_TITULOS = {
|
||||
owner: "Por Ejecutivo",
|
||||
tipo: "Por Tipo de Oportunidad",
|
||||
origen: "Por Origen de Oportunidad",
|
||||
};
|
||||
const IND_TOP = { owner: undefined, tipo: undefined, origen: 7 };
|
||||
const DIM_LABELS = { owner: "Ejecutivo", tipo: "Tipo", origen: "Origen", competidor: "Competidor", luz: "Luz Amarilla", plan: "Plan de Cierre", calidad: "Calidad", mov: "Movimiento", actAgendada: "Agendado" };
|
||||
|
||||
const PREVIS_TIPOS = ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling"];
|
||||
const PREVIS_PLANES_EXCL = ["Sin plan de cierre", "Plan D - Recalificar"];
|
||||
const ATRASADAS = "__ATRASADAS__";
|
||||
|
||||
const BLOCKER_INFO = {
|
||||
precio: { label: "Precio / oferta no competitiva", accion: "Evaluar un acelerador puntual: descuento, mes de cortesía o ajuste de instalación." },
|
||||
aprobacion: { label: "Esperando aprobación interna del cliente", accion: "Escalar con una llamada ejecutivo a gerente para destrabar la firma." },
|
||||
licitacion: { label: "Proceso de licitación externo", accion: "Fuera de control directo por ahora — mantener la relación." },
|
||||
};
|
||||
|
||||
function classifyBlocker(txt) {
|
||||
txt = (txt || "").toLowerCase();
|
||||
if (/licitaci|licitatorio/.test(txt)) return "licitacion";
|
||||
if (/precio|tarifa|descuento|presupuesto|\bcost[oa]\b|\bcara\b|instalaci[oó]n/.test(txt)) return "precio";
|
||||
if (/aprobaci|aprobar|aprob[oó]|gerencia|gerente|\bfirma\b|firmar|comit[eé]/.test(txt)) return "aprobacion";
|
||||
return null;
|
||||
}
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export default async function PrevisionPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner, w: winParam } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const hoy = currentMonth();
|
||||
const filt = parseFiltParam(sp.f);
|
||||
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||
const mze = sp.mze;
|
||||
|
||||
// Ventas logradas del mes en curso (acumulado al día de hoy): mismas oportunidades ganadas que
|
||||
// «Ventas logradas» (Resumen) en «Este mes» — tipos que cuentan para meta, valor real, solo por el
|
||||
// filtro de Propietario (no por la ventana ni los chips de esta página).
|
||||
const rangoMes = rangoDePeriodo("mes");
|
||||
|
||||
let allRows, allUsers, actividades, ganadasMes;
|
||||
try {
|
||||
[allRows, allUsers, actividades, ganadasMes] = await Promise.all([
|
||||
getPipeline(session.accessToken, scope),
|
||||
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
getActividades(session.accessToken, scope),
|
||||
getClosedRange(session.accessToken, scope, 1, rangoMes.from, rangoMes.to, undefined, VENTA_TYPE_FILTER),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const ventasMes = ganadasMes.reduce((a, o) => a + (o.actual || 0), 0);
|
||||
const ventasMesN = ganadasMes.length;
|
||||
const ventasMesArpu = ventasMesN ? ventasMes / ventasMesN : 0;
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||
|
||||
const base = allRows.filter((o) => PREVIS_TIPOS.includes(o.tipo) && !PREVIS_PLANES_EXCL.includes(o.plan));
|
||||
const atrasadas = base.filter((o) => !o.mesCierre || o.mesCierre < hoy);
|
||||
const win = winParam === ATRASADAS ? ATRASADAS : periodoPrevisionActivo(winParam);
|
||||
const hoyIso = new Date().toISOString().slice(0, 10);
|
||||
let pWinRaw, ini, fin;
|
||||
if (win === ATRASADAS) {
|
||||
pWinRaw = atrasadas;
|
||||
ini = hoyIso;
|
||||
fin = "9999-12-31";
|
||||
} else {
|
||||
const rango = rangoDePeriodoPrevision(win);
|
||||
pWinRaw = base.filter((o) => o.close && o.close >= rango.from && o.close < rango.to);
|
||||
ini = rango.from;
|
||||
fin = rango.finIncl;
|
||||
}
|
||||
const pWin = decorarActividadVentana(pWinRaw, actividades, ini, fin);
|
||||
const p = applyFilt(pWin, filt);
|
||||
const stageDurations = indActive === "vel" ? await getStageDurations(p.map((o) => o.id), session.accessToken) : [];
|
||||
|
||||
const est = p.reduce((a, o) => a + o.est, 0);
|
||||
const fc = p.reduce((a, o) => a + o.fc, 0);
|
||||
const estanc = p.filter((o) => o.estanc);
|
||||
const prioAltaPantalla = p.filter((o) => esPrioridadAlta(o));
|
||||
const metaGlobal = getMetaGlobal();
|
||||
const coverage = metaGlobal ? Math.round((fc / metaGlobal) * 100) : null;
|
||||
|
||||
// Informe de Previsión — solo con un único propietario seleccionado (ver mismo criterio en
|
||||
// tuberia/page.js). Usa `base` (todo lo elegible de previsión para esa persona, sin la ventana
|
||||
// de mes ni el filtro `f` activos) para no mezclar el snapshot del informe con lo que se esté
|
||||
// mirando en pantalla.
|
||||
const ownerName = scope.emails?.length === 1
|
||||
? session.isAdmin
|
||||
? allUsers.find((u) => u.email === scope.emails[0])?.name
|
||||
: session.user?.name
|
||||
: null;
|
||||
let previsionReportContent = null;
|
||||
if (ownerName) {
|
||||
const meta = getMetas()[scope.emails[0]] || null;
|
||||
const baseOwner = base.filter((o) => o.owner === ownerName);
|
||||
const proxMes = mesSiguiente(hoy);
|
||||
const pMes = baseOwner.filter((o) => o.mesCierre === hoy);
|
||||
const pProx = baseOwner.filter((o) => o.mesCierre === proxMes);
|
||||
const fcMes = pMes.reduce((a, o) => a + o.fc, 0);
|
||||
const fcProx = pProx.reduce((a, o) => a + o.fc, 0);
|
||||
const estMes = pMes.reduce((a, o) => a + o.est, 0);
|
||||
const coberturaMes = meta ? Math.round((fcMes / meta) * 100) : null;
|
||||
const brecha = meta ? Math.max(0, meta - fcMes) : 0;
|
||||
const prioAlta = pMes.filter((o) => esPrioridadAlta(o));
|
||||
const prioAltaEst = prioAlta.reduce((a, o) => a + o.est, 0);
|
||||
const bloqueadas = { precio: [], aprobacion: [], licitacion: [] };
|
||||
pMes.forEach((o) => {
|
||||
const cat = classifyBlocker(o.estado);
|
||||
if (cat) bloqueadas[cat].push(o);
|
||||
});
|
||||
const subibles = pMes
|
||||
.filter((o) => (o.plan === "Plan B - En Negociación" || o.plan === "Plan C - En seguimiento") && !o.estanc && !bloqueadas.precio.includes(o) && !bloqueadas.aprobacion.includes(o))
|
||||
.sort((a, b) => b.fc - a.fc);
|
||||
const estancSinBloqueo = pMes.filter((o) => o.estanc && !classifyBlocker(o.estado));
|
||||
const upsideNoPonderado = estMes - fcMes;
|
||||
const faltante = Math.max(0, brecha - upsideNoPonderado);
|
||||
const pipelineNuevoNecesario = faltante > 0 ? Math.round(faltante / 0.3) : 0;
|
||||
const diagClass = meta == null ? "info" : coberturaMes >= 100 ? "info" : coberturaMes >= 70 ? "warn" : "bad";
|
||||
const nombre = ownerName.split(" ")[0];
|
||||
const lblMesCap = MESLBL_CAP[hoy.slice(5, 7)] || hoy;
|
||||
const lblProxCap = MESLBL_CAP[proxMes.slice(5, 7)] || proxMes;
|
||||
|
||||
previsionReportContent = (
|
||||
<>
|
||||
<div style={{ borderBottom: "3px solid var(--ancla)", paddingBottom: 16, marginBottom: 20, display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 10 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".06em", color: "var(--tinta-suave)" }}>Informe de previsión — {lblMesCap}</div>
|
||||
<h2 style={{ margin: "4px 0 0", color: "var(--ancla)", fontSize: 24 }}>{ownerName}</h2>
|
||||
</div>
|
||||
<div style={{ textAlign: "right", fontSize: 12, color: "var(--tinta-suave)" }}>Solo Plan de Cierre A, B o C</div>
|
||||
</div>
|
||||
<div className="kpis rep-kpis" style={{ marginBottom: 14 }}>
|
||||
<div className="kpi"><span className="n">{money(ventasMes)}</span><span className="l">Ventas logradas {lblMesCap} (acumulado)</span><span className="sub">{ventasMesN} oport. · ARPU {money(ventasMesArpu)}</span></div>
|
||||
{meta &&<div className="kpi"><span className="n">{money(meta)}</span><span className="l">Meta de {lblMesCap}</span></div>}
|
||||
<div className="kpi"><span className="n">{money(fcMes)}</span><span className="l">Forecast ponderado {lblMesCap}</span></div>
|
||||
{meta && <div className="kpi"><span className={`n ${coberturaMes < 100 ? "pierde" : ""}`}>{coberturaMes}%</span><span className="l">Cobertura de meta</span></div>}
|
||||
{meta && brecha > 0 && <div className="kpi"><span className="n pierde">{money(brecha)}</span><span className="l">Brecha a la meta</span></div>}
|
||||
<div className="kpi"><span className="n" style={{ color: PRIORIDAD_COLOR.Alta.fg }}>{prioAlta.length}</span><span className="l">Prioridad alta · {money(prioAltaEst)} MRR est.</span></div>
|
||||
<div className="kpi"><span className="n">{money(fcProx)}</span><span className="l">Forecast ponderado {lblProxCap}</span></div>
|
||||
</div>
|
||||
<p style={{ margin: "0 0 8px", fontSize: 11, color: "var(--tinta-suave)" }}>Indicadores de toda la previsión abierta de {nombre} (Plan A, B o C, todos los meses de cierre); KPIs y tablas son del mes.</p>
|
||||
<PanelesPrevision p={baseOwner} />
|
||||
<div className={`callout ${diagClass}`}>
|
||||
{meta == null ? (
|
||||
<><b>{nombre} aún no tiene meta individual cargada</b> — este informe muestra el forecast pero no puede calcular cobertura ni brecha.</>
|
||||
) : coberturaMes >= 100 ? (
|
||||
<><b>{nombre} va bien encaminada: el forecast ponderado ({money(fcMes)}) ya cubre el {coberturaMes}% de su meta ({money(meta)}).</b> El foco esta semana es consolidar lo que sigue abierto, no solo cubrir el número.</>
|
||||
) : (
|
||||
<><b>Hay una brecha de {money(brecha)} para llegar a la meta de {lblMesCap} ({money(meta)}).</b> Así se cierra, en orden de impacto:</>
|
||||
)}
|
||||
</div>
|
||||
{bloqueadas.precio.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>1. Palanca de precio — {bloqueadas.precio.length} oport. · {money(bloqueadas.precio.reduce((a, o) => a + o.fc, 0))} ponderado en juego</h3>
|
||||
<p className="hint">{BLOCKER_INFO.precio.accion}</p>
|
||||
<AccionTable prevision list={bloqueadas.precio} />
|
||||
</div>
|
||||
)}
|
||||
{bloqueadas.aprobacion.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>2. Palanca de aprobación interna — {bloqueadas.aprobacion.length} oport. · {money(bloqueadas.aprobacion.reduce((a, o) => a + o.fc, 0))} ponderado en juego</h3>
|
||||
<p className="hint">{BLOCKER_INFO.aprobacion.accion}</p>
|
||||
<AccionTable prevision list={bloqueadas.aprobacion} />
|
||||
</div>
|
||||
)}
|
||||
{subibles.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>3. Subir de plan esta semana — {subibles.length} oport. en Plan B/C activas</h3>
|
||||
<p className="hint">Sin bloqueo ni estancamiento, por forecast ponderado. Subirlas a Plan A es lo que más rápido sube la cobertura.</p>
|
||||
<AccionTable prevision list={subibles} />
|
||||
</div>
|
||||
)}
|
||||
{estancSinBloqueo.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>4. Reactivar sin motivo claro — {estancSinBloqueo.length} oport. estancadas</h3>
|
||||
<p className="hint">Sin razón en las notas: necesitan un toque esta semana.</p>
|
||||
<AccionTable prevision list={estancSinBloqueo} />
|
||||
</div>
|
||||
)}
|
||||
{bloqueadas.licitacion.length > 0 && (
|
||||
<div className="callout info">
|
||||
<b>{bloqueadas.licitacion.length} oportunidad(es) en licitación externa</b> ({money(bloqueadas.licitacion.reduce((a, o) => a + o.fc, 0))} ponderado) — fuera de control directo este mes, mantener la relación.
|
||||
</div>
|
||||
)}
|
||||
{meta && faltante > 0 && (
|
||||
<div className="callout bad">
|
||||
<b>Aun empujando todas las palancas de arriba, el pipeline actual de {lblMesCap} no alcanza la meta.</b> Si todo lo de la tubería cerrara, el máximo es {money(estMes)} — faltarían {money(faltante)} para cubrir la brecha. Se necesitaría generar aproximadamente <b>{money(pipelineNuevoNecesario)}</b> de MRR nuevo esta semana para llegar a la meta.
|
||||
</div>
|
||||
)}
|
||||
<div className="callout warn" style={{ marginTop: 22 }}>
|
||||
<b>{lblProxCap}: {money(fcProx)} de forecast ({pProx.length} oport.)</b>{meta && ` vs. una meta de ${money(meta)} — ${Math.round((fcProx / meta) * 100)}% cubierto hoy.`}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const groups = { precio: [], aprobacion: [], licitacion: [] };
|
||||
p.forEach((o) => {
|
||||
const cat = classifyBlocker(o.estado);
|
||||
if (cat) groups[cat].push(o);
|
||||
});
|
||||
|
||||
const accionablesBlock = (
|
||||
<>
|
||||
{Object.entries(groups).some(([, v]) => v.length > 0) && (
|
||||
<div className="panel sec-oscura" style={{ marginTop: 18 }}>
|
||||
<h3>Oportunidades para accionar esta semana</h3>
|
||||
<p className="hint">Clasificado por palabras clave en "Estado de la Negociación" de Dynamics.</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(groups)
|
||||
.filter(([, list]) => list.length > 0)
|
||||
.map(([key, list]) => {
|
||||
const gEst = list.reduce((a, o) => a + o.est, 0);
|
||||
const gFc = list.reduce((a, o) => a + o.fc, 0);
|
||||
return (
|
||||
<div style={{ marginBottom: 16 }} key={key}>
|
||||
<div className="panel" style={{ marginBottom: 8, paddingBottom: 10 }}>
|
||||
<h3>
|
||||
{BLOCKER_INFO[key].label} — {list.length} oport. · {money(gEst)} est. · {money(gFc)} ponderado
|
||||
</h3>
|
||||
<p className="hint" style={{ margin: 0 }}>{BLOCKER_INFO[key].accion}</p>
|
||||
</div>
|
||||
<TablaPrevision arr={list} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
|
||||
const linkFor = (w) => {
|
||||
const params = new URLSearchParams();
|
||||
if (owner) params.set("owner", owner);
|
||||
params.set("w", w);
|
||||
return `/prevision?${params.toString()}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Previsión de Ventas</h2>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
|
||||
<ReportModal
|
||||
buttonLabel="📈 Informe de Previsión"
|
||||
disabled={!ownerName}
|
||||
disabledTitle="Selecciona un solo ejecutivo en Propietario para generar su informe individual."
|
||||
>
|
||||
{previsionReportContent}
|
||||
</ReportModal>
|
||||
<OwnerControl
|
||||
owners={owners}
|
||||
current={scope.locked ? [session.email] : scope.emails}
|
||||
locked={scope.locked}
|
||||
lockedLabel={session.email}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="hint" style={{ marginBottom: 8 }}>
|
||||
Solo Plan de Cierre A, B o C (sin "Sin plan" ni "Plan D - Recalificar").
|
||||
</p>
|
||||
|
||||
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||
{atrasadas.length > 0 && (
|
||||
<a href={linkFor(ATRASADAS)}>
|
||||
<button className={win === ATRASADAS ? "on" : ""} type="button">
|
||||
⚠ Atrasadas ({atrasadas.length})
|
||||
</button>
|
||||
</a>
|
||||
)}
|
||||
{PERIODOS_PREVISION.map((p) => (
|
||||
<a key={p.k} href={linkFor(p.k)}>
|
||||
<button className={win === p.k ? "on" : ""} type="button">
|
||||
{p.lbl}
|
||||
</button>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="kpis kpis-leg">
|
||||
<div className="kpi">
|
||||
<span className="n">{money(ventasMes)}</span>
|
||||
<span className="l">Ventas logradas en {MESLBL_CAP[hoy.slice(5, 7)] || "el mes"} (acumulado)</span>
|
||||
<span className="sub">{ventasMesN} oportunidades · ARPU {money(ventasMesArpu)}</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{p.length}</span>
|
||||
<span className="l">Oportunidades en esta ventana</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(est)}</span>
|
||||
<span className="l">Valor estimado (MRR)</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n" style={{ color: PRIORIDAD_COLOR.Alta.fg }}>{prioAltaPantalla.length}</span>
|
||||
<span className="l">Alta Prioridad · <b>{money(prioAltaPantalla.reduce((a, o) => a + o.est, 0))}</b> MRR est.</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(fc)}</span>
|
||||
<span className="l">Forecast ponderado</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={coverage != null && coverage < 100 ? "n pierde" : "n"}>
|
||||
{coverage != null ? `${coverage}%` : "n/d"}
|
||||
</span>
|
||||
<span className="l">Coverage vs meta equipo ({money(metaGlobal)})</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n pierde">{estanc.length}</span>
|
||||
<span className="l">En riesgo (estancadas)</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="callout warn">
|
||||
<b>Forecast ponderado = Σ (MRR estimado × probabilidad del Plan de Cierre).</b> Pesos: Plan A 90% · Plan B
|
||||
60% · Plan C 30%.
|
||||
</div>
|
||||
|
||||
{p.length > 0 && <ExecMatrix arr={p} titulo="Forecast por ejecutivo" valor={(o) => o.fc} hint="Forecast ponderado (MRR × peso del plan) por ejecutivo y Plan de Cierre" activeDim={mze} />}
|
||||
|
||||
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
{pWin.length === 0 ? (
|
||||
<p>No hay oportunidades en esta ventana.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="ind-grid">
|
||||
<Panel title="Forecast por Plan de Cierre" rows={aggOrd(p, "plan", PLAN_ORDER, (o) => o.fc)} byVal keepOrder dimKey="plan" />
|
||||
{hayClasif(p) && <MatrizCalidad arr={p} soloMovimiento />}
|
||||
<Panel
|
||||
title="Luz Amarilla — qué la detiene"
|
||||
hint="Bloqueador declarado por el ejecutivo"
|
||||
rows={agg(p, "luz", (o) => o.fc)}
|
||||
cls="alerta"
|
||||
top={7}
|
||||
byVal
|
||||
dimKey="luz"
|
||||
/>
|
||||
<div>
|
||||
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||
</div>
|
||||
{indActive === "vel" ? (
|
||||
<VelPanel
|
||||
title="Velocidad de movimiento"
|
||||
hint={`Días promedio en cada fase ya completada, de las ${p.length} oportunidades con cierre en el período que ves ahora`}
|
||||
vel={pipeVelFor(p, stageDurations)}
|
||||
/>
|
||||
) : (
|
||||
<Panel
|
||||
title={IND_TITULOS[indActive]}
|
||||
hint="Ordenado por forecast ponderado"
|
||||
rows={agg(p, indActive, (o) => o.fc)}
|
||||
top={IND_TOP[indActive]}
|
||||
byVal
|
||||
dimKey={indActive}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Panel title="Por Competidor" hint="Ordenado por forecast ponderado" rows={agg(p, "competidor", (o) => o.fc)} top={7} byVal dimKey="competidor" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="panel sec-oscura" style={{ paddingBottom: 12 }}>
|
||||
<h3>Oportunidades con cierre estimado en esta ventana</h3>
|
||||
<p className="hint">Forecast = MRR × peso del plan</p>
|
||||
<div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 8 }}>
|
||||
{ACTAGENDADA_ORDEN.map((k) => {
|
||||
const g = p.filter((o) => o.actAgendada === k);
|
||||
const con = k === ACTAGENDADA_ORDEN[0];
|
||||
return (
|
||||
<FilterableRow as="div" key={k} pairs={[["actAgendada", k]]} className="mtz-c" style={{ flexDirection: "row", gap: 10, alignItems: "center", padding: "6px 12px", borderLeft: `4px solid ${con ? "#3f7d5c" : "#B23A2E"}` }} title="Clic para filtrar la tabla">
|
||||
<span className="n" style={{ color: con ? "#3f7d5c" : "#B23A2E" }}>{g.length}</span>
|
||||
<span style={{ fontSize: 12 }}>{con ? "con actividad agendada" : "sin actividad agendada"} · <b>{money(g.reduce((s, o) => s + o.fc, 0))}</b></span>
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<TablaPrevision arr={p} />
|
||||
{accionablesBlock}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AyudaPrevision />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/renovaciones/logradas/loading.js
Normal file
4
app/renovaciones/logradas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
150
app/renovaciones/logradas/page.js
Normal file
150
app/renovaciones/logradas/page.js
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import { auth } from "../../lib/auth";
|
||||
import { ownerFilter } from "../../lib/authz";
|
||||
import { getRenovClosed, getSystemUsers } from "../../lib/queries";
|
||||
import { agg, EJECUTIVOS_RENOV } from "../../lib/derive";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
import OwnerControl from "../../components/OwnerControl";
|
||||
import ErrorNotice from "../../components/ErrorNotice";
|
||||
import Panel from "../../components/pipeline/Panel";
|
||||
import WonTable from "../../components/pipeline/WonTable";
|
||||
import FilterChips from "../../components/FilterChips";
|
||||
import FilterableRow from "../../components/FilterableRow";
|
||||
import { money, money2 } from "../../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DIM_LABELS = { tipo: "Momento", owner: "Ejecutivo", linea: "Línea de Negocio", servicio: "Servicio", origen: "Origen", cliente: "Cliente" };
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function retencion(w, l) {
|
||||
const t = w.length + l.length;
|
||||
return t ? Math.round((w.length / t) * 100) : null;
|
||||
}
|
||||
|
||||
export default async function RenovLogradasPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const mes = currentMonth();
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
let wonRaw, lostRaw, allUsers;
|
||||
try {
|
||||
[wonRaw, lostRaw, allUsers] = await Promise.all([
|
||||
getRenovClosed(session.accessToken, scope, 1, mes),
|
||||
getRenovClosed(session.accessToken, scope, 2, mes),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||
const won = applyFilt(wonRaw.map((o) => ({ ...o, val: o.actual })), filt);
|
||||
const lost = applyFilt(lostRaw, filt);
|
||||
|
||||
const sumW = won.reduce((a, o) => a + o.val, 0);
|
||||
const sumL = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||
const ret = retencion(won, lost);
|
||||
const aTiempo = won.filter((o) => o.tipo === "Próximo a Vencer en 30/60/90").length;
|
||||
const pctATiempo = won.length ? Math.round((aTiempo / won.length) * 100) : 0;
|
||||
|
||||
// Retención por ejecutivo — ganadas vs. perdidas de cada quien, en MRR.
|
||||
const ejecutivos = [...new Set([...won.map((o) => o.owner), ...lost.map((o) => o.owner)])];
|
||||
const retPorEjec = ejecutivos
|
||||
.map((ow) => ({
|
||||
k: ow,
|
||||
gana: won.filter((o) => o.owner === ow).reduce((a, o) => a + o.val, 0),
|
||||
pierde: lost.filter((o) => o.owner === ow).reduce((a, o) => a + (o.est || 0), 0),
|
||||
}))
|
||||
.sort((a, b) => b.gana + b.pierde - (a.gana + a.pierde));
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Renovaciones Logradas — {mes}</h2>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{money2(sumW)}</span><span className="l">MRR renovado</span></div>
|
||||
<div className="kpi"><span className="n">{won.length}</span><span className="l">Renovaciones logradas</span></div>
|
||||
<div className="kpi">
|
||||
<span className={`n ${ret != null && ret < 80 ? "pierde" : ""}`}>{ret == null ? "n/d" : `${ret}%`}</span>
|
||||
<span className="l">Tasa de retención (ganadas ÷ cerradas)</span>
|
||||
</div>
|
||||
<div className="kpi"><span className="n pierde">{money2(sumL)}</span><span className="l">MRR perdido por no renovar</span></div>
|
||||
<div className="kpi"><span className="n">{money2(won.length ? sumW / won.length : 0)}</span><span className="l">Ticket promedio renovado</span></div>
|
||||
<div className="kpi">
|
||||
<span className={`n ${pctATiempo < 50 ? "pierde" : ""}`}>{pctATiempo}%</span>
|
||||
<span className="l">Renovadas ANTES de vencer</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`callout ${ret != null && ret < 80 ? "warn" : "info"}`}>
|
||||
<b>De cada 100 contratos que se cerraron este mes, se conservaron {ret == null ? "—" : ret}.</b> Acá no hay
|
||||
meta que cumplir: la meta comercial excluye renovaciones a propósito, porque mide negocio nuevo y de
|
||||
expansión. Eso no las hace menores. El número que sí manda acá es la retención, y el costo de fallar es
|
||||
churn.
|
||||
</div>
|
||||
{pctATiempo < 50 && (
|
||||
<div className="callout warn">
|
||||
<b>Solo {pctATiempo}% se renovó antes de vencer</b> ({aTiempo} de {won.length}). El resto se firmó con el contrato ya vencido, cuando el cliente está más expuesto a la competencia.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{retPorEjec.length > 0 && (
|
||||
<div className="panel">
|
||||
<h3>Retención por ejecutivo</h3>
|
||||
<p className="hint">Ganadas vs. perdidas de cada quien, en MRR</p>
|
||||
{retPorEjec.map((r) => {
|
||||
const max = Math.max(...retPorEjec.flatMap((x) => [x.gana, x.pierde]), 0.1);
|
||||
return (
|
||||
<FilterableRow
|
||||
as="div"
|
||||
key={r.k}
|
||||
pairs={[["owner", r.k]]}
|
||||
className="cwm-row"
|
||||
style={{ padding: "7px 4px", borderBottom: "1px solid var(--linea)" }}
|
||||
>
|
||||
<div style={{ fontSize: 12.5, marginBottom: 5 }}>{r.k}</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
|
||||
<span style={{ fontSize: 10, color: "var(--gana)", width: 52 }}>Gana</span>
|
||||
<div className="bar-cell"><div className="bar-fill" style={{ width: `${(r.gana / max) * 100}%` }} /></div>
|
||||
<span className="v">{money2(r.gana)}</span>
|
||||
</div>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||
<span style={{ fontSize: 10, color: "var(--pierde)", width: 52 }}>Pierde</span>
|
||||
<div className="bar-cell"><div className="bar-fill pierde" style={{ width: `${(r.pierde / max) * 100}%` }} /></div>
|
||||
<span className="v">{money2(r.pierde)}</span>
|
||||
</div>
|
||||
</FilterableRow>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="grid3">
|
||||
<Panel title="Por momento de la renovación" hint="A tiempo vs. tarde" rows={agg(won, "tipo", (o) => o.val)} dimKey="tipo" />
|
||||
<Panel title="Por Ejecutivo" hint="Ordenado por MRR renovado" rows={agg(won, "owner", (o) => o.val)} dimKey="owner" />
|
||||
<Panel title="Por Línea de Negocio" hint="Ordenado por MRR renovado" rows={agg(won, "linea", (o) => o.val)} dimKey="linea" />
|
||||
<Panel title="Por Servicio / Producto" hint="Ordenado por MRR renovado" rows={agg(won, "servicio", (o) => o.val)} top={7} dimKey="servicio" />
|
||||
<Panel title="Por Origen" hint="Canal registrado de la oportunidad" rows={agg(won, "origen", (o) => o.val)} top={7} dimKey="origen" />
|
||||
<Panel title="Por Cliente" hint="Las cuentas que más MRR renovaron" rows={agg(won, "cliente", (o) => o.val)} top={7} dimKey="cliente" />
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Detalle de renovaciones logradas</h3>
|
||||
</div>
|
||||
{won.length === 0 ? <p>No hay renovaciones logradas en este período para este filtro.</p> : <WonTable rows={won} locked={scope.locked} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/renovaciones/perdidas/loading.js
Normal file
4
app/renovaciones/perdidas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
151
app/renovaciones/perdidas/page.js
Normal file
151
app/renovaciones/perdidas/page.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import { auth } from "../../lib/auth";
|
||||
import { ownerFilter } from "../../lib/authz";
|
||||
import { getRenovClosed, getMotivosCierre, getSystemUsers } from "../../lib/queries";
|
||||
import { agg, EJECUTIVOS_RENOV, catsWonLost } from "../../lib/derive";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
import OwnerControl from "../../components/OwnerControl";
|
||||
import ErrorNotice from "../../components/ErrorNotice";
|
||||
import Panel from "../../components/pipeline/Panel";
|
||||
import ComparePanelMotivo from "../../components/pipeline/ComparePanelMotivo";
|
||||
import FilterChips from "../../components/FilterChips";
|
||||
import { DYN, money2 } from "../../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const DIM_LABELS = { linea: "Línea de Negocio", motivo: "Motivo", tipo: "Momento", competidor: "Competidor", owner: "Ejecutivo", servicio: "Servicio" };
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function retencion(w, l) {
|
||||
const t = w.length + l.length;
|
||||
return t ? Math.round((w.length / t) * 100) : null;
|
||||
}
|
||||
|
||||
export default async function RenovPerdidasPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const mes = currentMonth();
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
let lostRaw, wonRaw, allUsers;
|
||||
try {
|
||||
[lostRaw, wonRaw, allUsers] = await Promise.all([
|
||||
getRenovClosed(session.accessToken, scope, 2, mes),
|
||||
getRenovClosed(session.accessToken, scope, 1, mes),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
const motivos = await getMotivosCierre(lostRaw.map((o) => o.id), session.accessToken);
|
||||
lostRaw = lostRaw.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor || o.competidor }));
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||
const lost = applyFilt(lostRaw, filt);
|
||||
const won = applyFilt(wonRaw, filt);
|
||||
|
||||
const sumL = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||
const ret = retencion(won, lost);
|
||||
const churn = ret == null ? null : 100 - ret;
|
||||
const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||
const conMotivo = lost.length - depu;
|
||||
const catsLinea = catsWonLost(won, lost, "linea");
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Renovaciones Perdidas — {mes}</h2>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n pierde">{lost.length}</span><span className="l">Contratos no renovados</span></div>
|
||||
<div className="kpi"><span className="n pierde">{money2(sumL)}</span><span className="l">MRR perdido</span></div>
|
||||
<div className="kpi">
|
||||
<span className={`n ${churn != null && churn > 20 ? "pierde" : ""}`}>{churn == null ? "n/d" : `${churn}%`}</span>
|
||||
<span className="l">Churn del período</span>
|
||||
</div>
|
||||
<div className="kpi"><span className="n">{conMotivo}</span><span className="l">Con motivo real declarado</span></div>
|
||||
<div className="kpi"><span className="n">{money2(lost.length ? sumL / lost.length : 0)}</span><span className="l">Ticket promedio perdido</span></div>
|
||||
</div>
|
||||
|
||||
<div className="callout warn">
|
||||
<b>Cada contrato de esta lista es MRR que ya estaba adentro y se fue.</b>{" "}
|
||||
{depu > 0 && (
|
||||
<><b>{depu} de {lost.length}</b> cerraron como Envejecida/Cancelada/Agotada (depuración, no rechazo del cliente); la causa real se lee en las{" "}
|
||||
{conMotivo} restantes. </>
|
||||
)}
|
||||
Ojo: <b>WhatsApp no está en Dynamics</b>; un motivo vacío es «sin motivo en el CRM», no «no se gestionó».
|
||||
</div>
|
||||
|
||||
{catsLinea.length > 0 && (
|
||||
<ComparePanelMotivo
|
||||
title="Renovación por línea de negocio: qué se conserva y qué se va"
|
||||
hint="Ganadas vs. perdidas en MRR, por línea de negocio"
|
||||
cats={catsLinea}
|
||||
dimKey="linea"
|
||||
/>
|
||||
)}
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="grid3">
|
||||
<Panel title="Motivo de cierre" hint="Fuente: Cierre de oportunidad en Dynamics" rows={agg(lost, "motivo", (o) => o.est)} cls="pierde" dimKey="motivo" />
|
||||
<Panel title="Por momento de la renovación" hint="¿Se perdió antes o después de vencer el contrato?" rows={agg(lost, "tipo", (o) => o.est)} cls="pierde" dimKey="tipo" />
|
||||
<Panel
|
||||
title="Competidor"
|
||||
hint="Contra quién se perdió"
|
||||
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Sin registrar"), "competidor", (o) => o.est)}
|
||||
cls="pierde"
|
||||
top={7}
|
||||
dimKey="competidor"
|
||||
/>
|
||||
<Panel title="Por Ejecutivo" hint="Ordenado por MRR perdido" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" dimKey="owner" />
|
||||
<Panel title="Por Línea de Negocio" hint="Ordenado por MRR perdido" rows={agg(lost, "linea", (o) => o.est)} cls="pierde" dimKey="linea" />
|
||||
<Panel title="Por Servicio / Producto" hint="Ordenado por MRR perdido" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" top={7} dimKey="servicio" />
|
||||
</div>
|
||||
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Detalle de contratos no renovados</h3>
|
||||
</div>
|
||||
{lost.length === 0 ? (
|
||||
<p>No hay renovaciones perdidas en este período para este filtro.</p>
|
||||
) : (
|
||||
<div className="tw">
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Cliente</th>
|
||||
<th>Oportunidad</th>
|
||||
<th>Motivo de cierre</th>
|
||||
<th>Línea de Negocio</th>
|
||||
{!scope.locked && <th>Ejecutivo</th>}
|
||||
<th className="num">MRR est.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td>{o.cliente || "—"}</td>
|
||||
<td><a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a></td>
|
||||
<td>{o.motivo}</td>
|
||||
<td>{o.linea || "—"}</td>
|
||||
{!scope.locked && <td>{o.owner}</td>}
|
||||
<td className="num">{o.est ? money2(o.est) : "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/renovaciones/prevision/loading.js
Normal file
4
app/renovaciones/prevision/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
367
app/renovaciones/prevision/page.js
Normal file
367
app/renovaciones/prevision/page.js
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
import { auth } from "../../lib/auth";
|
||||
import { ownerFilter } from "../../lib/authz";
|
||||
import { getRenovPipeline, getRenovClosed, getSystemUsers, getActividades, getStageDurations } from "../../lib/queries";
|
||||
import { agg, aggOrd, EJECUTIVOS_RENOV, decorarActividadVentana, ACTAGENDADA_ORDEN, pipeVelFor } from "../../lib/derive";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
import OwnerControl from "../../components/OwnerControl";
|
||||
import ErrorNotice from "../../components/ErrorNotice";
|
||||
import Panel from "../../components/pipeline/Panel";
|
||||
import TablaPipe from "../../components/pipeline/TablaPipe";
|
||||
import ExecMatrix from "../../components/pipeline/ExecMatrix";
|
||||
import VelPanel from "../../components/pipeline/VelPanel";
|
||||
import SegTabs from "../../components/SegTabs";
|
||||
import FilterChips from "../../components/FilterChips";
|
||||
import ReportModal from "../../components/ReportModal";
|
||||
import PanelesCalidad from "../../components/pipeline/PanelesCalidad";
|
||||
import AccionTable from "../../components/pipeline/AccionTable";
|
||||
import RepTable from "../../components/pipeline/RepTable";
|
||||
import { money } from "../../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||
|
||||
const BLOCKER_INFO = {
|
||||
precio: { label: "Precio / oferta no competitiva", accion: "Evaluar un acelerador puntual: descuento, mes de cortesía o ajuste de instalación." },
|
||||
aprobacion: { label: "Esperando aprobación interna del cliente", accion: "Escalar con una llamada ejecutivo a gerente para destrabar la firma." },
|
||||
licitacion: { label: "Proceso de licitación externo", accion: "Fuera de control directo por ahora — mantener la relación." },
|
||||
};
|
||||
function classifyBlocker(txt) {
|
||||
txt = (txt || "").toLowerCase();
|
||||
if (/licitaci|licitatorio/.test(txt)) return "licitacion";
|
||||
if (/precio|tarifa|descuento|presupuesto|\bcost[oa]\b|\bcara\b|instalaci[oó]n/.test(txt)) return "precio";
|
||||
if (/aprobaci|aprobar|aprob[oó]|gerencia|gerente|\bfirma\b|firmar|comit[eé]/.test(txt)) return "aprobacion";
|
||||
return null;
|
||||
}
|
||||
function mesSiguiente(m) {
|
||||
const [y, mm] = m.split("-").map(Number);
|
||||
const d = new Date(y, mm, 1);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const IND_TABS = [
|
||||
{ k: "owner", lbl: "Ejecutivo" },
|
||||
{ k: "cliente", lbl: "Cliente" },
|
||||
{ k: "linea", lbl: "Línea" },
|
||||
{ k: "competidor", lbl: "Competidor" },
|
||||
{ k: "vel", lbl: "Velocidad" },
|
||||
];
|
||||
const IND_TITULOS = {
|
||||
owner: "Por Ejecutivo",
|
||||
cliente: "Por Cliente",
|
||||
linea: "Por Línea de Negocio",
|
||||
competidor: "Por Competidor",
|
||||
};
|
||||
const IND_HINTS = {
|
||||
owner: "Ordenado por MRR en juego",
|
||||
cliente: "Las cuentas con más MRR por renovar este mes",
|
||||
linea: "Ordenado por MRR en juego",
|
||||
competidor: "Contra quién se compite la renovación",
|
||||
};
|
||||
const IND_TOP = { owner: undefined, cliente: 7, linea: undefined, competidor: 7 };
|
||||
const DIM_LABELS = { owner: "Ejecutivo", cliente: "Cliente", linea: "Línea", competidor: "Competidor", tipo: "Momento", actAgendada: "Agendado" };
|
||||
|
||||
const ATRASADAS = "__ATRASADAS__";
|
||||
const MESLBL_CAP = {
|
||||
"01": "Enero", "02": "Febrero", "03": "Marzo", "04": "Abril", "05": "Mayo", "06": "Junio",
|
||||
"07": "Julio", "08": "Agosto", "09": "Septiembre", "10": "Octubre", "11": "Noviembre", "12": "Diciembre",
|
||||
};
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
function mesAnterior(m, n) {
|
||||
const [y, mm] = m.split("-").map(Number);
|
||||
const d = new Date(y, mm - 1 - n, 1);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
function ventanaDeMes(win, hoyIso) {
|
||||
if (win === ATRASADAS) return { ini: hoyIso, fin: "9999-12-31" };
|
||||
const [y, m] = win.split("-").map(Number);
|
||||
const fin = new Date(y, m, 0);
|
||||
return { ini: `${win}-01`, fin: `${fin.getFullYear()}-${String(fin.getMonth() + 1).padStart(2, "0")}-${String(fin.getDate()).padStart(2, "0")}` };
|
||||
}
|
||||
|
||||
export default async function RenovPrevisionPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner, w: winParam } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const hoy = currentMonth();
|
||||
const filt = parseFiltParam(sp.f);
|
||||
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||
const mze = sp.mze;
|
||||
|
||||
let allRows, allUsers, historico, actividades;
|
||||
try {
|
||||
[allRows, allUsers, actividades] = await Promise.all([
|
||||
getRenovPipeline(session.accessToken, scope),
|
||||
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
getActividades(session.accessToken, scope, EJECUTIVOS_RENOV),
|
||||
]);
|
||||
// Referencia honesta: MRR realmente renovado en los 3 meses cerrados anteriores.
|
||||
const meses3 = [mesAnterior(hoy, 1), mesAnterior(hoy, 2), mesAnterior(hoy, 3)];
|
||||
const won3 = await Promise.all(meses3.map((m) => getRenovClosed(session.accessToken, scope, 1, m)));
|
||||
historico = won3.map((w) => w.reduce((a, o) => a + (o.actual || 0), 0));
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||
const histProm = historico.length ? historico.reduce((a, b) => a + b, 0) / historico.length : 0;
|
||||
|
||||
// Informe de Previsión de Renovación — solo con un único propietario seleccionado. `historico`/
|
||||
// `histProm` de arriba ya vienen filtrados por `scope` — cuando hay un solo propietario
|
||||
// seleccionado (condición para que `ownerName` exista), esas consultas ya son de esa persona:
|
||||
// no hace falta volver a pedirle a Dynamics el histórico.
|
||||
const ownerName = scope.emails?.length === 1
|
||||
? session.isAdmin
|
||||
? allUsers.find((u) => u.email === scope.emails[0])?.name
|
||||
: session.user?.name
|
||||
: null;
|
||||
let renovPrevisionReportContent = null;
|
||||
if (ownerName) {
|
||||
const baseOwner = allRows.filter((o) => o.owner === ownerName);
|
||||
const proxMes = mesSiguiente(hoy);
|
||||
const atrasadasOwner = baseOwner.filter((o) => !o.mesCierre || o.mesCierre < hoy);
|
||||
const atrasadasEst = atrasadasOwner.reduce((a, o) => a + o.est, 0);
|
||||
const pMesOwner = baseOwner.filter((o) => o.mesCierre === hoy);
|
||||
const pProxOwner = baseOwner.filter((o) => o.mesCierre === proxMes);
|
||||
const fcMesOwner = pMesOwner.reduce((a, o) => a + o.fc, 0);
|
||||
const fcProxOwner = pProxOwner.reduce((a, o) => a + o.fc, 0);
|
||||
const cobMes = histProm ? Math.round((fcMesOwner / histProm) * 100) : null;
|
||||
const bloqueadas = { precio: [], aprobacion: [], licitacion: [] };
|
||||
pMesOwner.forEach((o) => {
|
||||
const cat = classifyBlocker(o.estado);
|
||||
if (cat) bloqueadas[cat].push(o);
|
||||
});
|
||||
const subibles = pMesOwner
|
||||
.filter((o) => (o.plan === "Plan B - En Negociación" || o.plan === "Plan C - En seguimiento") && !o.estanc && !bloqueadas.precio.includes(o) && !bloqueadas.aprobacion.includes(o))
|
||||
.sort((a, b) => b.fc - a.fc);
|
||||
const estancSinBloqueo = pMesOwner.filter((o) => o.estanc && !classifyBlocker(o.estado));
|
||||
const diagClass = histProm === 0 ? "info" : cobMes >= 100 ? "info" : cobMes >= 70 ? "warn" : "bad";
|
||||
const lblMesCap = MESLBL_CAP[hoy.slice(5, 7)] || hoy;
|
||||
const lblProxCap = MESLBL_CAP[proxMes.slice(5, 7)] || proxMes;
|
||||
|
||||
renovPrevisionReportContent = (
|
||||
<>
|
||||
<div style={{ borderBottom: "3px solid var(--ancla)", paddingBottom: 16, marginBottom: 20, display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 10 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".06em", color: "var(--tinta-suave)" }}>Informe de previsión de renovaciones — {lblMesCap}</div>
|
||||
<h2 style={{ margin: "4px 0 0", color: "var(--ancla)", fontSize: 24 }}>{ownerName}</h2>
|
||||
</div>
|
||||
<div style={{ textAlign: "right", fontSize: 12, color: "var(--tinta-suave)" }}>Incluye oportunidades sin Plan de Cierre — el contrato vence igual</div>
|
||||
</div>
|
||||
<div className="kpis" style={{ marginBottom: 18 }}>
|
||||
<div className="kpi"><span className={`n ${atrasadasOwner.length ? "pierde" : ""}`}>{atrasadasOwner.length}</span><span className="l">Ya vencidas y sin cerrar · {money(atrasadasEst)}</span></div>
|
||||
<div className="kpi"><span className="n">{money(fcMesOwner)}</span><span className="l">Forecast ponderado {lblMesCap}</span></div>
|
||||
{histProm > 0 && <div className="kpi"><span className={`n ${cobMes < 100 ? "pierde" : ""}`}>{cobMes}%</span><span className="l">vs. promedio renovado últimos 3 meses ({money(histProm)})</span></div>}
|
||||
<div className="kpi"><span className="n">{money(fcProxOwner)}</span><span className="l">Forecast ponderado {lblProxCap}</span></div>
|
||||
</div>
|
||||
<PanelesCalidad p={pMesOwner} />
|
||||
<div className={`callout ${diagClass}`}>
|
||||
{histProm === 0 ? (
|
||||
<><b>{ownerName.split(" ")[0]} no tiene renovaciones ganadas en los 3 meses anteriores</b> — este informe muestra el forecast de {lblMesCap} pero sin un piso histórico propio contra qué compararlo.</>
|
||||
) : cobMes >= 100 ? (
|
||||
<><b>El forecast ponderado de {lblMesCap} ({money(fcMesOwner)}) ya iguala o supera lo renovado en promedio los últimos 3 meses ({money(histProm)}).</b> El foco es sostener el ritmo, no solo cubrir el número.</>
|
||||
) : (
|
||||
<><b>El forecast ponderado de {lblMesCap} ({money(fcMesOwner)}) queda por debajo del promedio renovado los últimos 3 meses ({money(histProm)}).</b> Así se cierra la brecha, en orden de impacto:</>
|
||||
)}
|
||||
</div>
|
||||
{bloqueadas.precio.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>1. Palanca de precio — {bloqueadas.precio.length} oport. · {money(bloqueadas.precio.reduce((a, o) => a + o.fc, 0))} ponderado en juego</h3>
|
||||
<p className="hint">{BLOCKER_INFO.precio.accion}</p>
|
||||
<AccionTable list={bloqueadas.precio} />
|
||||
</div>
|
||||
)}
|
||||
{bloqueadas.aprobacion.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>2. Palanca de aprobación interna — {bloqueadas.aprobacion.length} oport. · {money(bloqueadas.aprobacion.reduce((a, o) => a + o.fc, 0))} ponderado en juego</h3>
|
||||
<p className="hint">{BLOCKER_INFO.aprobacion.accion}</p>
|
||||
<AccionTable list={bloqueadas.aprobacion} />
|
||||
</div>
|
||||
)}
|
||||
{subibles.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>3. Subir de plan esta semana — {subibles.length} oport. en Plan B/C activas</h3>
|
||||
<p className="hint">Sin bloqueo ni estancamiento, por forecast ponderado.</p>
|
||||
<AccionTable list={subibles} />
|
||||
</div>
|
||||
)}
|
||||
{estancSinBloqueo.length > 0 && (
|
||||
<div className="panel" style={{ marginBottom: 14 }}>
|
||||
<h3>4. Reactivar sin motivo claro — {estancSinBloqueo.length} oport. estancadas</h3>
|
||||
<p className="hint">Sin razón en las notas: necesitan un toque esta semana.</p>
|
||||
<AccionTable list={estancSinBloqueo} />
|
||||
</div>
|
||||
)}
|
||||
{bloqueadas.licitacion.length > 0 && (
|
||||
<div className="callout info">
|
||||
<b>{bloqueadas.licitacion.length} renovación(es) en licitación externa</b> ({money(bloqueadas.licitacion.reduce((a, o) => a + o.fc, 0))} ponderado) — fuera de control directo este mes, mantener la relación.
|
||||
</div>
|
||||
)}
|
||||
{atrasadasOwner.length > 0 && (
|
||||
<>
|
||||
<div className="callout bad" style={{ marginTop: 22 }}>
|
||||
<b>{atrasadasOwner.length} renovaciones ya pasaron su fecha estimada y siguen abiertas</b> ({money(atrasadasEst)} de MRR expuesto)
|
||||
</div>
|
||||
<RepTable arr={atrasadasOwner} />
|
||||
</>
|
||||
)}
|
||||
<div className="callout warn" style={{ marginTop: 22 }}>
|
||||
<b>{lblProxCap}: {money(fcProxOwner)} de forecast ({pProxOwner.length} renovaciones)</b> por vencer el mes siguiente.
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const futuros = [...new Set(allRows.map((o) => o.mesCierre).filter((m) => m && m >= hoy))].sort();
|
||||
const atrasadas = allRows.filter((o) => !o.mesCierre || o.mesCierre < hoy);
|
||||
const win = winParam === ATRASADAS ? ATRASADAS : futuros.includes(winParam) ? winParam : futuros[0] || hoy;
|
||||
const hoyIso = new Date().toISOString().slice(0, 10);
|
||||
const { ini, fin: finVentana } = ventanaDeMes(win, hoyIso);
|
||||
const pWinRaw = win === ATRASADAS ? atrasadas : allRows.filter((o) => o.mesCierre === win);
|
||||
const pWin = decorarActividadVentana(pWinRaw, actividades, ini, finVentana);
|
||||
const p = applyFilt(pWin, filt);
|
||||
const stageDurations = indActive === "vel" ? await getStageDurations(p.map((o) => o.id), session.accessToken) : [];
|
||||
const winLbl = win === ATRASADAS ? "renovaciones atrasadas (fecha estimada ya vencida)" : MESLBL_CAP[win.slice(5, 7)] || win;
|
||||
|
||||
const est = p.reduce((a, o) => a + o.est, 0);
|
||||
const fc = p.reduce((a, o) => a + o.fc, 0);
|
||||
const estanc = p.filter((o) => o.estanc);
|
||||
const sinPlan = p.filter((o) => o.plan === "Sin plan de cierre");
|
||||
const cob = histProm ? Math.round((fc / histProm) * 100) : null;
|
||||
|
||||
const porMes = futuros.map((m) => ({
|
||||
lbl: MESLBL_CAP[m.slice(5, 7)] || m,
|
||||
n: allRows.filter((o) => o.mesCierre === m).length,
|
||||
est: allRows.filter((o) => o.mesCierre === m).reduce((a, o) => a + o.est, 0),
|
||||
}));
|
||||
|
||||
const linkFor = (w) => {
|
||||
const params = new URLSearchParams();
|
||||
if (owner) params.set("owner", owner);
|
||||
params.set("w", w);
|
||||
return `/renovaciones/prevision?${params.toString()}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Previsión de Renovaciones</h2>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
|
||||
<ReportModal
|
||||
buttonLabel="📈 Informe de Previsión"
|
||||
disabled={!ownerName}
|
||||
disabledTitle="Selecciona un solo ejecutivo en Propietario para generar su informe individual."
|
||||
>
|
||||
{renovPrevisionReportContent}
|
||||
</ReportModal>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||
{atrasadas.length > 0 && (
|
||||
<a href={linkFor(ATRASADAS)}>
|
||||
<button className={win === ATRASADAS ? "on" : ""} type="button">⚠ Atrasadas ({atrasadas.length})</button>
|
||||
</a>
|
||||
)}
|
||||
{futuros.map((m) => (
|
||||
<a key={m} href={linkFor(m)}>
|
||||
<button className={win === m ? "on" : ""} type="button">{MESLBL_CAP[m.slice(5, 7)] || m}</button>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{p.length}</span><span className="l">Renovaciones que vencen en {winLbl}</span></div>
|
||||
<div className="kpi"><span className="n">{money(est)}</span><span className="l">MRR en juego</span></div>
|
||||
<div className="kpi"><span className="n">{money(fc)}</span><span className="l">Forecast ponderado</span></div>
|
||||
<div className="kpi">
|
||||
<span className={`n ${cob != null && cob < 100 ? "pierde" : ""}`}>{cob == null ? "n/d" : `${cob}%`}</span>
|
||||
<span className="l">vs. promedio renovado últimos 3 meses ({money(histProm)})</span>
|
||||
</div>
|
||||
<div className="kpi"><span className="n pierde">{estanc.length}</span><span className="l">En riesgo (estancadas)</span></div>
|
||||
</div>
|
||||
|
||||
<div className={`callout ${cob != null && cob < 100 ? "warn" : "info"}`}>
|
||||
{win === ATRASADAS ? (
|
||||
<><b>Estas {p.length} renovaciones ya pasaron su fecha estimada y siguen abiertas.</b> En renovación el
|
||||
tiempo juega en contra de forma literal: el contrato vence igual, con o sin gestión. </>
|
||||
) : (
|
||||
<><b>{winLbl}: {money(est)} de MRR vence este mes</b> en {p.length} contratos, con un forecast ponderado
|
||||
de {money(fc)}. </>
|
||||
)}
|
||||
<b>Acá no se compara contra meta</b> — la meta comercial no incluye renovaciones. La referencia útil es lo
|
||||
que se renovó de verdad en los 3 meses anteriores ({money(histProm)} en promedio). <b>Forecast ponderado =
|
||||
Σ (MRR × peso del Plan de Cierre)</b>: A 90% · B 60% · C 30% · sin plan 10%.
|
||||
</div>
|
||||
{sinPlan.length > 0 && (
|
||||
<div className="callout warn">
|
||||
<b>{sinPlan.length} de estas {p.length} no tienen Plan de Cierre</b> ({money(sinPlan.reduce((a, o) => a + o.est, 0))}).
|
||||
A diferencia de Previsión de Ventas, acá <b>se cuentan</b> (el contrato vence tenga plan o no) y pesan solo 10% en el ponderado.
|
||||
</div>
|
||||
)}
|
||||
{porMes.length > 1 && (
|
||||
<div className="callout warn">
|
||||
<b>Vencimientos por delante:</b> {porMes.map((m) => `${m.lbl} — ${money(m.est)} (${m.n})`).join(" · ")}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{p.length > 0 && <ExecMatrix arr={p} titulo="Renovaciones por vencer, por ejecutivo" hint="Monto = MRR en juego" activeDim={mze} />}
|
||||
|
||||
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
{pWin.length === 0 ? (
|
||||
<p>No hay renovaciones en esta ventana.</p>
|
||||
) : (
|
||||
<div className="split23">
|
||||
<div className="split23-ind">
|
||||
<Panel
|
||||
title="Por momento de la renovación"
|
||||
hint="Ya vencido vs. próximo a vencer"
|
||||
rows={agg(p, "tipo", (o) => o.est)}
|
||||
cls="alerta"
|
||||
dimKey="tipo"
|
||||
/>
|
||||
<Panel
|
||||
title="¿Ya se agendó algo?"
|
||||
hint={`Tarea/Cita/Llamada dentro de ${winLbl}`}
|
||||
rows={aggOrd(p, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
|
||||
cls="alerta"
|
||||
dimKey="actAgendada"
|
||||
/>
|
||||
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||
</div>
|
||||
{indActive === "vel" ? (
|
||||
<VelPanel
|
||||
title="Velocidad de movimiento"
|
||||
hint={`Días promedio en cada fase ya completada, de las ${p.length} renovaciones que ves ahora`}
|
||||
vel={pipeVelFor(p, stageDurations)}
|
||||
/>
|
||||
) : (
|
||||
<Panel
|
||||
title={IND_TITULOS[indActive]}
|
||||
hint={IND_HINTS[indActive]}
|
||||
rows={agg(p, indActive, (o) => o.est)}
|
||||
top={IND_TOP[indActive]}
|
||||
dimKey={indActive}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Renovaciones con vencimiento en {winLbl}</h3>
|
||||
<p className="hint">Forecast = MRR × peso del plan</p>
|
||||
</div>
|
||||
<TablaPipe arr={p} tipo="fc" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/renovaciones/tuberia/loading.js
Normal file
4
app/renovaciones/tuberia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
227
app/renovaciones/tuberia/page.js
Normal file
227
app/renovaciones/tuberia/page.js
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
import { auth } from "../../lib/auth";
|
||||
import { ownerFilter } from "../../lib/authz";
|
||||
import { getRenovPipeline, getSystemUsers, getActividades, getStageDurations } from "../../lib/queries";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
import OwnerControl from "../../components/OwnerControl";
|
||||
import ErrorNotice from "../../components/ErrorNotice";
|
||||
import Panel from "../../components/pipeline/Panel";
|
||||
import TablaPipe from "../../components/pipeline/TablaPipe";
|
||||
import ExecMatrix from "../../components/pipeline/ExecMatrix";
|
||||
import VelPanel from "../../components/pipeline/VelPanel";
|
||||
import SegTabs from "../../components/SegTabs";
|
||||
import FilterChips from "../../components/FilterChips";
|
||||
import ReportModal from "../../components/ReportModal";
|
||||
import PanelesCalidad from "../../components/pipeline/PanelesCalidad";
|
||||
import RepTable from "../../components/pipeline/RepTable";
|
||||
import { money } from "../../lib/constants";
|
||||
import { EJECUTIVOS_RENOV, agg, aggOrd, cierreVencido, decorarActividadVentana, ACTAGENDADA_ORDEN, pipeVelFor } from "../../lib/derive";
|
||||
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||
|
||||
function currentMonth() {
|
||||
const d = new Date();
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const IND_TABS = [
|
||||
{ k: "owner", lbl: "Ejecutivo" },
|
||||
{ k: "cliente", lbl: "Cliente" },
|
||||
{ k: "linea", lbl: "Línea" },
|
||||
{ k: "competidor", lbl: "Competidor" },
|
||||
{ k: "vel", lbl: "Velocidad" },
|
||||
];
|
||||
const IND_TITULOS = {
|
||||
owner: "Por Ejecutivo",
|
||||
cliente: "Por Cliente",
|
||||
linea: "Por Línea de Negocio",
|
||||
competidor: "Por Competidor",
|
||||
};
|
||||
const IND_HINTS = {
|
||||
owner: "Ordenado por MRR en juego",
|
||||
cliente: "Las cuentas con más MRR por renovar",
|
||||
linea: "Ordenado por MRR en juego",
|
||||
competidor: "Contra quién se compite la renovación",
|
||||
};
|
||||
const IND_TOP = { owner: undefined, cliente: 7, linea: undefined, competidor: 7 };
|
||||
const DIM_LABELS = { owner: "Ejecutivo", cliente: "Cliente", linea: "Línea", competidor: "Competidor", tipo: "Momento", actAgendada: "Agendado" };
|
||||
|
||||
export default async function RenovTuberiaPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const { owner } = sp;
|
||||
const scope = ownerFilter(session, owner);
|
||||
const filt = parseFiltParam(sp.f);
|
||||
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||
const mze = sp.mze;
|
||||
|
||||
let pipelineRows, allUsers, actividades;
|
||||
try {
|
||||
[pipelineRows, allUsers, actividades] = await Promise.all([
|
||||
getRenovPipeline(session.accessToken, scope),
|
||||
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
getActividades(session.accessToken, scope, EJECUTIVOS_RENOV),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||
const hoy = new Date().toISOString().slice(0, 10);
|
||||
const allRows = decorarActividadVentana(pipelineRows, actividades, hoy, "9999-12-31");
|
||||
const rows = applyFilt(allRows, filt);
|
||||
const stageDurations = indActive === "vel" ? await getStageDurations(rows.map((o) => o.id), session.accessToken) : [];
|
||||
|
||||
const totalEst = rows.reduce((a, r) => a + r.est, 0);
|
||||
const totalFc = rows.reduce((a, r) => a + r.fc, 0);
|
||||
const estanc = rows.filter((r) => r.estanc);
|
||||
const estancEst = estanc.reduce((a, r) => a + r.est, 0);
|
||||
const sinPlan = rows.filter((r) => r.plan === "Sin plan de cierre");
|
||||
const sinPlanEst = sinPlan.reduce((a, r) => a + r.est, 0);
|
||||
const vencidas = rows.filter(cierreVencido);
|
||||
const yaVencido = rows.filter((r) => r.tipo === "Contrato vencido");
|
||||
const pctSinPlan = rows.length ? Math.round((sinPlan.length / rows.length) * 100) : 0;
|
||||
|
||||
// Informe de Renovación — solo con un único propietario seleccionado (ver mismo criterio en
|
||||
// tuberia/page.js de Ventas). Usa `allRows` (sin el filtro `f` activo): es un snapshot completo.
|
||||
const ownerName = scope.emails?.length === 1
|
||||
? session.isAdmin
|
||||
? allUsers.find((u) => u.email === scope.emails[0])?.name
|
||||
: session.user?.name
|
||||
: null;
|
||||
let renovReportContent = null;
|
||||
if (ownerName) {
|
||||
const p = allRows.filter((o) => o.owner === ownerName);
|
||||
const est = p.reduce((a, o) => a + o.est, 0);
|
||||
const fc = p.reduce((a, o) => a + o.fc, 0);
|
||||
const yaVencidoP = p.filter((o) => o.tipo === "Contrato vencido");
|
||||
const hoyMes = currentMonth();
|
||||
const actuar = p
|
||||
.filter((o) => (o.mesCierre && o.mesCierre < hoyMes) || (o.mesCierre === hoyMes && o.plan !== "Plan A - En firma" && o.plan !== "Plan B - En Negociación"))
|
||||
.sort((a, b) => b.est - a.est);
|
||||
const tocar = p.filter((o) => o.actividad === "Fría" || o.actividad === "Congelada").sort((a, b) => b.est - a.est);
|
||||
const enfocarse = p.filter((o) => (o.plan === "Plan A - En firma" || o.plan === "Plan B - En Negociación") && !o.estanc).sort((a, b) => b.fc - a.fc);
|
||||
|
||||
renovReportContent = (
|
||||
<>
|
||||
<div style={{ borderBottom: "3px solid var(--ancla)", paddingBottom: 16, marginBottom: 20, display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 10 }}>
|
||||
<div>
|
||||
<div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".06em", color: "var(--tinta-suave)" }}>Informe de renovaciones individual</div>
|
||||
<h2 style={{ margin: "4px 0 0", color: "var(--ancla)", fontSize: 24 }}>{ownerName}</h2>
|
||||
</div>
|
||||
<div style={{ textAlign: "right", fontSize: 12, color: "var(--tinta-suave)" }}>No cuenta para la meta comercial — el indicador es retención</div>
|
||||
</div>
|
||||
<div className="kpis" style={{ marginBottom: 18 }}>
|
||||
<div className="kpi"><span className="n">{p.length}</span><span className="l">Renovaciones abiertas</span></div>
|
||||
<div className="kpi"><span className="n">{money(est)}</span><span className="l">MRR en juego</span></div>
|
||||
<div className="kpi"><span className="n">{money(fc)}</span><span className="l">Forecast ponderado</span></div>
|
||||
<div className="kpi"><span className="n pierde">{yaVencidoP.length}</span><span className="l">Con el contrato ya vencido</span></div>
|
||||
<div className="kpi"><span className="n pierde">{p.filter((o) => o.estanc).length}</span><span className="l">Estancadas</span></div>
|
||||
</div>
|
||||
<PanelesCalidad p={p} />
|
||||
<div className="callout bad"><b>🔴 Actuar ya ({actuar.length})</b> — contrato vencido, o vence este/próximo mes sin un plan sólido.</div>
|
||||
<RepTable arr={actuar} />
|
||||
<div className="callout warn" style={{ marginTop: 22 }}><b>🟡 Tocar — frías o congeladas ({tocar.length})</b> — más de 30-60 días sin avanzar o sin actividad.</div>
|
||||
<RepTable arr={tocar} />
|
||||
<div className="callout info" style={{ marginTop: 22 }}><b>🟢 Encaminadas — con tracción real ({enfocarse.length})</b> — Plan A/B, avanzando bien y sin estancarse.</div>
|
||||
<RepTable arr={enfocarse} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Tubería de Renovaciones</h2>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
|
||||
<ReportModal
|
||||
buttonLabel="📊 Informe de Renovación"
|
||||
disabled={!ownerName}
|
||||
disabledTitle="Selecciona un solo ejecutivo en Propietario para generar su informe individual."
|
||||
>
|
||||
{renovReportContent}
|
||||
</ReportModal>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{money(totalEst)}</span><span className="l">MRR en juego (est.)</span></div>
|
||||
<div className="kpi"><span className="n">{rows.length}</span><span className="l">Renovaciones abiertas</span></div>
|
||||
<div className="kpi"><span className="n">{money(totalFc)}</span><span className="l">Forecast ponderado</span></div>
|
||||
<div className="kpi"><span className="n pierde">{yaVencido.length}</span><span className="l">Con el contrato YA vencido · {money(yaVencido.reduce((a, o) => a + o.est, 0))}</span></div>
|
||||
<div className="kpi"><span className="n pierde">{estanc.length}</span><span className="l">Estancadas · {money(estancEst)}</span></div>
|
||||
<div className="kpi"><span className="n pierde">{sinPlan.length}</span><span className="l">Sin plan de cierre · {money(sinPlanEst)}</span></div>
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<p>No hay renovaciones activas para este filtro.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="callout warn">
|
||||
<b>MRR que ya factura y hay que no perder:</b> <b>{money(totalEst)}</b> en{" "}
|
||||
{rows.length} renovaciones abiertas, <b>{yaVencido.length} con el contrato ya vencido</b>. <b>{estanc.length} de {rows.length}</b>{" "}
|
||||
están estancadas (+14 días sin actividad o +30 en la misma fase) por {money(estancEst)}, y{" "}
|
||||
<b>{vencidas.length}</b> pasaron su fecha estimada de cierre.
|
||||
</div>
|
||||
{pctSinPlan > 50 && (
|
||||
<div className="callout warn">
|
||||
<b>{pctSinPlan}% de la tubería de renovaciones no tiene Plan de Cierre</b> ({sinPlan.length} de{" "}
|
||||
{rows.length}, {money(sinPlanEst)}). Sin plan pesan solo 10% en el forecast: {sinPlan.length} contratos que vencen no tienen fecha de firma comprometida.
|
||||
</div>
|
||||
)}
|
||||
<ExecMatrix arr={rows} titulo="Renovaciones por ejecutivo" hint="Incluye Ventas y SAC" activeDim={mze} />
|
||||
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="split23">
|
||||
<div className="split23-ind">
|
||||
<Panel
|
||||
title="Por momento de la renovación"
|
||||
hint="Ya vencido vs. próximo a vencer"
|
||||
rows={agg(rows, "tipo", (o) => o.est)}
|
||||
cls="alerta"
|
||||
dimKey="tipo"
|
||||
/>
|
||||
<Panel
|
||||
title="¿Ya se agendó algo?"
|
||||
hint="Tarea/Cita/Llamada desde hoy en adelante"
|
||||
rows={aggOrd(rows, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
|
||||
cls="alerta"
|
||||
dimKey="actAgendada"
|
||||
/>
|
||||
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||
</div>
|
||||
{indActive === "vel" ? (
|
||||
<VelPanel
|
||||
title="Velocidad de movimiento"
|
||||
hint={`Días promedio en cada fase ya completada, de las ${rows.length} renovaciones abiertas que ves ahora`}
|
||||
vel={pipeVelFor(rows, stageDurations)}
|
||||
/>
|
||||
) : (
|
||||
<Panel
|
||||
title={IND_TITULOS[indActive]}
|
||||
hint={IND_HINTS[indActive]}
|
||||
rows={agg(rows, indActive, (o) => o.est)}
|
||||
top={IND_TOP[indActive]}
|
||||
dimKey={indActive}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||
<h3>Detalle de la tubería de renovaciones</h3>
|
||||
<p className="hint">
|
||||
<b>Plan</b>: A en firma · B negociación
|
||||
· C seguimiento · D recalificar · ⚠ cierre vencido
|
||||
</p>
|
||||
</div>
|
||||
<TablaPipe arr={rows} tipo="est" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/resumen/loading.js
Normal file
4
app/resumen/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
147
app/resumen/page.js
Normal file
147
app/resumen/page.js
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getClosedRange, getMotivosCierre, getSystemUsers, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { PROPIETARIOS_VENTA } from "../lib/derive";
|
||||
import { PERIODOS, periodoActivo, rangoDePeriodo } from "../lib/periodos";
|
||||
import { getMetas, getMetaGlobal } from "../lib/metas";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import SegTabs from "../components/SegTabs";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import DashBar from "../components/pipeline/DashBar";
|
||||
import DashDonut from "../components/pipeline/DashDonut";
|
||||
import WonTable from "../components/pipeline/WonTable";
|
||||
import { money2 } from "../lib/constants";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
|
||||
const DIM_LABELS = { owner: "Propietario", linea: "Línea de Negocio", tipo: "Tipo de Oportunidad", segmento: "Segmento", origen: "Origen", campaign: "Campaña" };
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function ResumenPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const scope = ownerFilter(session, sp.owner);
|
||||
const periodo = periodoActivo(sp.periodo);
|
||||
const { from, to, lbl: periodoLbl, mensual } = rangoDePeriodo(periodo);
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
let wonRaw, lostRaw, allUsers;
|
||||
try {
|
||||
[wonRaw, lostRaw, allUsers] = await Promise.all([
|
||||
getClosedRange(session.accessToken, scope, 1, from, to, undefined, VENTA_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, scope, 2, from, to, undefined, VENTA_TYPE_FILTER),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
const motivos = await getMotivosCierre(lostRaw.map((o) => o.id), session.accessToken);
|
||||
lostRaw = lostRaw.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar" }));
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
const owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
|
||||
// val en vez de actual, para que DashBar/DashDonut/WonTable (compartidos con Nuevas Oportunidades)
|
||||
// no necesiten dos convenciones de nombre de campo distintas.
|
||||
const won = applyFilt(wonRaw.map((o) => ({ ...o, val: o.actual })), filt);
|
||||
const lost = applyFilt(lostRaw, filt);
|
||||
|
||||
const sumW = won.reduce((a, o) => a + (o.val || 0), 0);
|
||||
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META) — no hace falta
|
||||
// re-filtrar.
|
||||
const sumWMeta = sumW;
|
||||
const arpu = won.length ? sumW / won.length : 0;
|
||||
|
||||
// Tasa de Ganancia Total (todo el denominador) vs. Real (excluye depuración de datos, que no es
|
||||
// pérdida de negocio real) — ver CLAUDE.md, lección "el forecast ponderado sobreestima" /
|
||||
// hallazgo Win Rate. Replicado de pages/resumen.js del sitio HTML.
|
||||
const depuN = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||
const lostRealN = lost.length - depuN;
|
||||
const convTotal = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
|
||||
const convReal = won.length + lostRealN ? Math.round((won.length / (won.length + lostRealN)) * 100) : 0;
|
||||
|
||||
const metas = getMetas();
|
||||
const selectedEmails = scope.locked ? [session.email] : scope.emails;
|
||||
// Un solo propietario → su meta individual · varios → la suma de las suyas · ninguno (todos) →
|
||||
// la meta global del equipo.
|
||||
const metaDen =
|
||||
selectedEmails.length === 1
|
||||
? metas[selectedEmails[0].toLowerCase()] || null
|
||||
: selectedEmails.length > 1
|
||||
? selectedEmails.reduce((s, e) => s + (metas[e.toLowerCase()] || 0), 0) || null
|
||||
: getMetaGlobal();
|
||||
// Cumplimiento compara contra una meta MENSUAL — solo tiene sentido para "este mes"/"mes
|
||||
// anterior"; una semana vs. una meta de mes entero da un % artificialmente bajo.
|
||||
const cumpl = mensual && metaDen ? Math.round((sumWMeta / metaDen) * 100) : null;
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Ventas logradas</h2>
|
||||
<OwnerControl
|
||||
owners={owners}
|
||||
current={scope.locked ? [session.email] : scope.emails}
|
||||
locked={scope.locked}
|
||||
lockedLabel={session.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={PERIODOS} activeKey={periodo} paramName="periodo" />
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{money2(sumW)}</span>
|
||||
<span className="l">Ingresos Reales (ganadas)</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{won.length}</span>
|
||||
<span className="l">Oportunidades ganadas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money2(arpu)}</span>
|
||||
<span className="l">ARPU logradas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n pierde">{lost.length}</span>
|
||||
<span className="l">Oportunidades perdidas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{convTotal}%</span>
|
||||
<span className="l">Tasa de Ganancia Total</span>
|
||||
</div>
|
||||
<div className="kpi" title={`Excluye ${depuN} pérdida(s) descartadas sin motivo real (depuración de datos)`}>
|
||||
<span className="n">{convReal}%</span>
|
||||
<span className="l">Tasa de Ganancia Real</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={cumpl != null && cumpl < 70 ? "n pierde" : "n"}>
|
||||
{cumpl != null ? cumpl + "%" : "n/d"}
|
||||
</span>
|
||||
<span className="l">
|
||||
Cumplimiento de meta
|
||||
{!mensual ? " (n/d — meta es mensual)" : metaDen ? ` (${money2(metaDen)})` : " (sin meta asignada)"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="hint">
|
||||
Mostrando {periodoLbl}. Solo Venta - Cliente Nuevo, Up-Selling, Cross-Selling y Plan de Cuenta (sin renovaciones ni SAC). Cumplimiento de meta solo en "Este mes"/"Mes anterior".
|
||||
</p>
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
<div className="grid2">
|
||||
<DashBar title="Propietario" arr={won} dimKey="owner" />
|
||||
<DashBar title="Línea de Negocio" arr={won} dimKey="linea" />
|
||||
<DashBar title="Tipo de Oportunidad" arr={won} dimKey="tipo" />
|
||||
<DashDonut title="Segmento" arr={won} dimKey="segmento" />
|
||||
<DashBar title="Origen de Oportunidad" arr={won} dimKey="origen" />
|
||||
<DashBar title="Ventas por Campaña de Origen" arr={won} dimKey="campaign" />
|
||||
</div>
|
||||
|
||||
<WonTable rows={won} title="Detalle de Oportunidades Ganadas" locked={scope.locked} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/tendencia/loading.js
Normal file
4
app/tendencia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
435
app/tendencia/page.js
Normal file
435
app/tendencia/page.js
Normal file
|
|
@ -0,0 +1,435 @@
|
|||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter } from "../lib/authz";
|
||||
import { getClosed, getSystemUsers, resolveScopeOwnerIds, VENTA_TYPE_FILTER } from "../lib/queries";
|
||||
import { PROPIETARIOS_VENTA, agg } from "../lib/derive";
|
||||
import { getMetas, getMetaGlobal } from "../lib/metas";
|
||||
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import SegTabs from "../components/SegTabs";
|
||||
import FilterChips from "../components/FilterChips";
|
||||
import Panel from "../components/pipeline/Panel";
|
||||
import WonTable from "../components/pipeline/WonTable";
|
||||
import BucketTabs from "../components/tendencia/BucketTabs";
|
||||
import { money, money2 } from "../lib/constants";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Simplificación consciente frente al sitio HTML: el grano de la serie es siempre MENSUAL (el HTML
|
||||
// baja a semana/día para períodos cortos — requeriría consultas día a día a Dynamics, demasiado
|
||||
// costoso en vivo). Por el mismo motivo no hay columna "Creadas" (viene de un JSON mantenido a mano
|
||||
// fuera de este pipeline, sin equivalente en vivo todavía).
|
||||
const TEND_MIN_N = 5; // cierres mínimos para que un ratio/observación sea interpretable — igual que el HTML.
|
||||
const DIM_LABELS = { segmento: "Segmento", linea: "Línea", tipo: "Tipo" };
|
||||
const PERIODOS = [
|
||||
{ k: "3", lbl: "3 meses" },
|
||||
{ k: "6", lbl: "6 meses" },
|
||||
{ k: "12", lbl: "12 meses" },
|
||||
{ k: "anio", lbl: "Año en curso" },
|
||||
{ k: "trimestre", lbl: "Trimestre en curso" },
|
||||
];
|
||||
const MESLBL3 = ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"];
|
||||
|
||||
function mesKey(d) {
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||
}
|
||||
function mesLbl(m) {
|
||||
const [y, mm] = m.split("-");
|
||||
return `${MESLBL3[+mm - 1]} ${y}`;
|
||||
}
|
||||
function lastMonths(n) {
|
||||
const out = [];
|
||||
const d = new Date();
|
||||
for (let i = n - 1; i >= 0; i--) out.push(mesKey(new Date(d.getFullYear(), d.getMonth() - i, 1)));
|
||||
return out;
|
||||
}
|
||||
function mesesDePeriodo(periodo) {
|
||||
const hoy = new Date();
|
||||
if (periodo === "anio") {
|
||||
const out = [];
|
||||
for (let m = 0; m <= hoy.getMonth(); m++) out.push(mesKey(new Date(hoy.getFullYear(), m, 1)));
|
||||
return out;
|
||||
}
|
||||
if (periodo === "trimestre") {
|
||||
const qStart = Math.floor(hoy.getMonth() / 3) * 3;
|
||||
const out = [];
|
||||
for (let m = qStart; m <= hoy.getMonth(); m++) out.push(mesKey(new Date(hoy.getFullYear(), m, 1)));
|
||||
return out;
|
||||
}
|
||||
return lastMonths(parseInt(periodo, 10) || 6);
|
||||
}
|
||||
function mediana(arr) {
|
||||
if (!arr.length) return 0;
|
||||
const s = [...arr].sort((a, b) => a - b);
|
||||
const m = Math.floor(s.length / 2);
|
||||
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
|
||||
}
|
||||
// Escala de color de magnitud por columna — mismo criterio que tendEscala() del HTML: azul de
|
||||
// marca, más intenso cuanto más alto dentro de la columna, calculado solo sobre buckets fiables.
|
||||
function escalaMag(v, min, max) {
|
||||
if (v == null || max <= min) return {};
|
||||
return { background: `rgba(30,113,184,${(0.05 + ((v - min) / (max - min)) * 0.28).toFixed(3)})` };
|
||||
}
|
||||
function escalaCumpl(p) {
|
||||
if (p == null) return {};
|
||||
return { background: p >= 70 ? "rgba(63,125,92,.20)" : p >= 50 ? "rgba(201,138,27,.22)" : "rgba(178,58,46,.16)" };
|
||||
}
|
||||
|
||||
export default async function TendenciaPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
|
||||
const sp = await searchParams;
|
||||
const scope = ownerFilter(session, sp.owner);
|
||||
const periodo = PERIODOS.some((p) => p.k === sp.periodo) ? sp.periodo : "6";
|
||||
const meses = mesesDePeriodo(periodo);
|
||||
const bucketSel = sp.t || null;
|
||||
const filt = parseFiltParam(sp.f);
|
||||
|
||||
// Un solo propietario → su meta individual · varios → la suma de las suyas · ninguno (todos) →
|
||||
// la meta global del equipo. Mismo criterio que resumen/page.js — comparar lo que vendió una
|
||||
// sola persona contra la meta de todo el equipo no informa nada (ver CLAUDE.md del proyecto).
|
||||
const metas = getMetas();
|
||||
const selectedEmails = scope.locked ? [session.email] : scope.emails;
|
||||
const metaDen =
|
||||
selectedEmails.length === 1
|
||||
? metas[selectedEmails[0].toLowerCase()] || null
|
||||
: selectedEmails.length > 1
|
||||
? selectedEmails.reduce((s, e) => s + (metas[e.toLowerCase()] || 0), 0) || null
|
||||
: getMetaGlobal();
|
||||
|
||||
let porMes, owners, wonAll, lostAll;
|
||||
try {
|
||||
const [{ ownerIds }, allUsers] = await Promise.all([
|
||||
resolveScopeOwnerIds(scope, session.accessToken),
|
||||
getSystemUsers(session.accessToken),
|
||||
]);
|
||||
owners = allUsers.filter((u) => PROPIETARIOS_VENTA.includes(u.name));
|
||||
|
||||
const crudo = await Promise.all(
|
||||
meses.map(async (m) => {
|
||||
const [won, lost] = await Promise.all([
|
||||
getClosed(session.accessToken, scope, 1, m, ownerIds, VENTA_TYPE_FILTER),
|
||||
getClosed(session.accessToken, scope, 2, m, ownerIds, VENTA_TYPE_FILTER),
|
||||
]);
|
||||
return { mes: m, won, lost };
|
||||
})
|
||||
);
|
||||
wonAll = crudo.flatMap((x) => x.won);
|
||||
lostAll = crudo.flatMap((x) => x.lost);
|
||||
|
||||
const hoyMes = mesKey(new Date());
|
||||
// sumW: TODO lo ganado del mes (para el gráfico/tabla, igual que Ganadas/Resumen). sumWMeta:
|
||||
// solo los 4 tipos que cuentan para meta — Renovaciones y SAC quedan afuera del cumplimiento a
|
||||
// propósito (ver CLAUDE.md, "Cumplimiento de meta — qué cuenta").
|
||||
porMes = crudo.map(({ mes, won: wonRaw, lost: lostRaw }) => {
|
||||
const won = applyFilt(wonRaw, filt);
|
||||
const lost = applyFilt(lostRaw, filt);
|
||||
const vals = won.map((o) => o.actual || 0).sort((a, b) => b - a);
|
||||
const sumW = vals.reduce((a, v) => a + v, 0);
|
||||
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META).
|
||||
const sumWMeta = sumW;
|
||||
const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||
const denomReal = won.length + lost.length - depu;
|
||||
return {
|
||||
mes,
|
||||
lbl: mesLbl(mes),
|
||||
won: won.length,
|
||||
lost: lost.length,
|
||||
sumW,
|
||||
mayor: vals[0] || 0,
|
||||
pctMayor: sumW ? Math.round(((vals[0] || 0) / sumW) * 100) : 0,
|
||||
mediana: mediana(vals),
|
||||
arpu: won.length ? sumW / won.length : 0,
|
||||
convReal: denomReal ? Math.round((won.length / denomReal) * 100) : null,
|
||||
meta: metaDen,
|
||||
cumpl: metaDen ? Math.round((sumWMeta / metaDen) * 100) : null,
|
||||
enCurso: mes === hoyMes,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
|
||||
const bSel = porMes.find((b) => b.mes === bucketSel) || null;
|
||||
|
||||
// Ámbito: todo el período o el bucket aislado — con el cross-filter ya aplicado.
|
||||
const wonFiltAll = applyFilt(wonAll, filt);
|
||||
const lostFiltAll = applyFilt(lostAll, filt);
|
||||
const enBucket = (o) => !bSel || (o.actualClose || "").slice(0, 7) === bSel.mes;
|
||||
const won = wonFiltAll.filter(enBucket);
|
||||
const lost = lostFiltAll.filter(enBucket);
|
||||
// Base para los paneles de dimensión: el bucket aislado + todo el cross-filter activo, incluida
|
||||
// la propia dimensión de cada panel — mismo criterio ya usado en ganadas/perdemos (a diferencia
|
||||
// del HTML, que excluye la dimensión propia de cada panel para poder seguir cambiando de
|
||||
// categoría sin limpiar el filtro primero; ver tendFilter(base, dim) en el HTML fuente).
|
||||
const baseDim = wonFiltAll.filter(enBucket);
|
||||
|
||||
const vals = won.map((o) => o.actual || 0);
|
||||
const ing = vals.reduce((a, v) => a + v, 0);
|
||||
const depuN = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||
const denomTotal = won.length + lost.length;
|
||||
const denomReal = denomTotal - depuN;
|
||||
const medianaT = mediana(vals);
|
||||
const prom = won.length ? ing / won.length : 0;
|
||||
const brecha = medianaT ? Math.round(((prom - medianaT) / medianaT) * 100) : 0;
|
||||
const convTotal = denomTotal ? Math.round((won.length / denomTotal) * 100) : 0;
|
||||
const convReal = denomReal ? Math.round((won.length / denomReal) * 100) : 0;
|
||||
|
||||
// El cumplimiento del KPI solo tiene sentido si el numerador cubre a las mismas personas que la
|
||||
// meta: filtrar por propietario (control de arriba) sigue siendo comparable — usa su meta
|
||||
// personal. Filtrar por segmento/línea/tipo no, porque nadie tiene una meta partida por producto.
|
||||
const metaCmp = ["segmento", "linea", "tipo"].some((d) => filt[d]) ? null : metaDen;
|
||||
// won ya viene acotado a VENTA_TYPE_FILTER (los mismos 4 tipos de TIPOS_META).
|
||||
const sumWMetaKpi = ing;
|
||||
const cumplKpi = metaCmp ? Math.round((sumWMetaKpi / metaCmp) * 100) : null;
|
||||
|
||||
const ambito = bSel ? bSel.lbl : PERIODOS.find((p) => p.k === periodo)?.lbl || "período";
|
||||
|
||||
// ---- Observaciones calculadas — solo aritmética verificable, nunca una conclusión causal (ver
|
||||
// cabecera de tendencia.js en el sitio HTML: "¿puede estar equivocada? si la respuesta no es un
|
||||
// no rotundo, no va"). ----
|
||||
const cerrados = porMes.filter((b) => !b.enCurso);
|
||||
const observaciones = [];
|
||||
const ultimo = porMes[porMes.length - 1];
|
||||
if (ultimo?.enCurso)
|
||||
observaciones.push(`${ultimo.lbl} está en curso (datos a hoy) — no es comparable con un mes cerrado.`);
|
||||
if (cerrados.length >= 2) {
|
||||
const a = cerrados[cerrados.length - 2],
|
||||
b = cerrados[cerrados.length - 1];
|
||||
const d = b.sumW - a.sumW,
|
||||
pct = a.sumW ? Math.round((d / a.sumW) * 100) : 0;
|
||||
observaciones.push(
|
||||
`De ${a.lbl} a ${b.lbl} el ingreso ${d >= 0 ? "subió" : "bajó"} ${money(Math.abs(d))} (${pct > 0 ? "+" : ""}${pct}%), con ${a.won} y ${b.won} cierres respectivamente.`
|
||||
);
|
||||
}
|
||||
porMes
|
||||
.filter((b) => b.won > 0 && b.pctMayor >= 30)
|
||||
.forEach((b) =>
|
||||
observaciones.push(`En ${b.lbl}, ${b.pctMayor}% del ingreso vino de una sola oportunidad (${money(b.mayor)} de ${money(b.sumW)}).`)
|
||||
);
|
||||
const flojos = porMes.filter((b) => b.won > 0 && b.won < TEND_MIN_N);
|
||||
if (flojos.length)
|
||||
observaciones.push(
|
||||
`${flojos.length} ${flojos.length === 1 ? "mes tiene" : "meses tienen"} menos de ${TEND_MIN_N} cierres (${flojos.map((b) => b.lbl).join(", ")}) — sus promedios y porcentajes no son interpretables.`
|
||||
);
|
||||
|
||||
// ---- Descomposición volumen × ticket — identidad aritmética exacta entre los extremos CERRADOS
|
||||
// de la serie que se está viendo (no los dos últimos meses: con un año a la vista, "julio a
|
||||
// agosto" no explica el año). ----
|
||||
const cerradosConDatos = porMes.filter((b) => !b.enCurso && b.won > 0);
|
||||
let desc = null;
|
||||
if (cerradosConDatos.length >= 2) {
|
||||
const a = cerradosConDatos[0],
|
||||
b = cerradosConDatos[cerradosConDatos.length - 1];
|
||||
const tA = a.sumW / a.won,
|
||||
tB = b.sumW / b.won;
|
||||
const efVol = (b.won - a.won) * tA,
|
||||
efTicket = b.won * (tB - tA),
|
||||
total = b.sumW - a.sumW;
|
||||
const suma = Math.abs(efVol) + Math.abs(efTicket) || 1;
|
||||
desc = { a, b, tA, tB, efVol, efTicket, total, suma, pctTot: a.sumW ? Math.round((total / a.sumW) * 100) : 0 };
|
||||
}
|
||||
const signo = (v) => `${v >= 0 ? "+" : "−"}${money(Math.abs(v))}`;
|
||||
|
||||
// ---- Tabla de detalle por mes ----
|
||||
const rIng = (() => {
|
||||
const vs = porMes.filter((b) => b.won > 0).map((b) => b.sumW);
|
||||
return vs.length ? [Math.min(...vs), Math.max(...vs)] : [0, 0];
|
||||
})();
|
||||
const rMed = (() => {
|
||||
const vs = porMes.filter((b) => b.won >= TEND_MIN_N).map((b) => b.mediana);
|
||||
return vs.length ? [Math.min(...vs), Math.max(...vs)] : [0, 0];
|
||||
})();
|
||||
const rConv = (() => {
|
||||
const vs = porMes.filter((b) => b.won >= TEND_MIN_N && b.convReal != null).map((b) => b.convReal);
|
||||
return vs.length ? [Math.min(...vs), Math.max(...vs)] : [0, 0];
|
||||
})();
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||
<h2>Tendencia</h2>
|
||||
<OwnerControl
|
||||
owners={owners}
|
||||
current={scope.locked ? [session.email] : scope.emails}
|
||||
locked={scope.locked}
|
||||
lockedLabel={session.email}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<SegTabs tabs={PERIODOS} activeKey={periodo} paramName="periodo" />
|
||||
</div>
|
||||
|
||||
<FilterChips dimLabels={DIM_LABELS} />
|
||||
|
||||
{observaciones.length > 0 && (
|
||||
<div className="callout info">
|
||||
<b>Observaciones del período</b>
|
||||
<ul style={{ margin: "8px 0 0", paddingLeft: 18 }}>
|
||||
{observaciones.map((o, i) => (
|
||||
<li key={i} style={{ marginBottom: 4 }}>
|
||||
{o}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi">
|
||||
<span className="n">{money2(ing)}</span>
|
||||
<span className="l">Ingreso — {ambito}</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{won.length}</span>
|
||||
<span className="l">Oportunidades ganadas</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(medianaT)}</span>
|
||||
<span className="l">Ticket mediano (el cierre típico)</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{money(prom)}</span>
|
||||
<span className="l">Ticket promedio{brecha > 0 ? ` · ${brecha}% sobre la mediana` : ""}</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="n">{convTotal}%</span>
|
||||
<span className="l">Tasa de Ganancia Total</span>
|
||||
</div>
|
||||
<div className="kpi" title={`Excluye ${depuN} pérdida(s) descartadas sin motivo real (depuración de datos)`}>
|
||||
<span className="n">{convReal}%</span>
|
||||
<span className="l">Tasa de Ganancia Real</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className={cumplKpi != null && cumplKpi < 70 ? "n pierde" : "n"}>{cumplKpi != null ? `${cumplKpi}%` : "n/d"}</span>
|
||||
<span className="l">{metaCmp ? `Cumplimiento (meta ${money(metaCmp)})` : "Cumplimiento — n/d con filtros activos"}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BucketTabs buckets={porMes} />
|
||||
|
||||
{desc && (
|
||||
<div className="panel">
|
||||
<h3>
|
||||
Qué movió el ingreso — {desc.a.lbl} a {desc.b.lbl}
|
||||
</h3>
|
||||
<p className="hint">
|
||||
Aporte de cada causa: cuántos negocios se cerraron y qué tan grande fue cada uno.
|
||||
</p>
|
||||
<div className="tdesc-tot">
|
||||
<span className="val">{money(desc.a.sumW)}</span>
|
||||
<span className="per">{desc.a.lbl}</span>
|
||||
<span className="fl">→</span>
|
||||
<span className="val">{money(desc.b.sumW)}</span>
|
||||
<span className="per">{desc.b.lbl}</span>
|
||||
<span className={`delta ${desc.total >= 0 ? "tdesc-up" : "tdesc-down"}`}>
|
||||
{signo(desc.total)} ({desc.pctTot > 0 ? "+" : ""}
|
||||
{desc.pctTot}%)
|
||||
</span>
|
||||
</div>
|
||||
<div className="tdesc-grid">
|
||||
<div className="tdesc-card">
|
||||
<div className="lbl">{desc.b.won - desc.a.won >= 0 ? "Se cerraron más negocios" : "Se cerraron menos negocios"}</div>
|
||||
<div className={`amt ${desc.efVol >= 0 ? "tdesc-up" : "tdesc-down"}`}>{signo(desc.efVol)}</div>
|
||||
<div className="bar-cell">
|
||||
<div
|
||||
className={`bar-fill ${desc.efVol < 0 ? "pierde" : ""}`}
|
||||
style={{ width: `${((Math.abs(desc.efVol) / desc.suma) * 100).toFixed(0)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="det">
|
||||
{desc.a.won} → {desc.b.won} cierres ({desc.b.won - desc.a.won >= 0 ? "+" : "−"}
|
||||
{Math.abs(desc.b.won - desc.a.won)}) · {Math.round((Math.abs(desc.efVol) / desc.suma) * 100)}% del cambio
|
||||
</div>
|
||||
</div>
|
||||
<div className="tdesc-card">
|
||||
<div className="lbl">{desc.tB - desc.tA >= 0 ? "Cada negocio fue más grande" : "Cada negocio fue más chico"}</div>
|
||||
<div className={`amt ${desc.efTicket >= 0 ? "tdesc-up" : "tdesc-down"}`}>{signo(desc.efTicket)}</div>
|
||||
<div className="bar-cell">
|
||||
<div
|
||||
className={`bar-fill ${desc.efTicket < 0 ? "pierde" : ""}`}
|
||||
style={{ width: `${((Math.abs(desc.efTicket) / desc.suma) * 100).toFixed(0)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="det">
|
||||
ticket {money(desc.tA)} → {money(desc.tB)} · {Math.round((Math.abs(desc.efTicket) / desc.suma) * 100)}% del cambio
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid2">
|
||||
<Panel title="Por segmento" hint="Clientes Nuevos (venta nueva) vs. Cartera Activa (ampliaciones)" rows={agg(baseDim, "segmento", (o) => o.actual)} dimKey="segmento" />
|
||||
<Panel title="Por línea de negocio" hint="Qué producto sostiene el ingreso del período" rows={agg(baseDim, "linea", (o) => o.actual)} dimKey="linea" />
|
||||
</div>
|
||||
<div className="grid2">
|
||||
<Panel title="Por tipo de oportunidad" hint="Venta nueva, ampliación, renovación o retención" rows={agg(baseDim, "tipo", (o) => o.actual)} dimKey="tipo" />
|
||||
</div>
|
||||
|
||||
<div className="tw" style={{ marginTop: 18 }}>
|
||||
<div className="tw-title">
|
||||
<h3>Detalle por mes</h3>
|
||||
<span className="tw-count">Ticket mediano = cierre típico, sin distorsión por un negocio grande.</span>
|
||||
</div>
|
||||
<div className="ts">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Mes</th>
|
||||
<th className="num">Cierres</th>
|
||||
<th className="num">Ingreso</th>
|
||||
<th className="num">Ticket mediano</th>
|
||||
<th className="num">Ticket promedio</th>
|
||||
<th className="num">% Conv. Real</th>
|
||||
<th className="num">Mayor deal</th>
|
||||
<th className="num">Meta</th>
|
||||
<th className="num">Cumpl.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{porMes.map((b) => {
|
||||
const flojo = b.won > 0 && b.won < TEND_MIN_N;
|
||||
return (
|
||||
<tr key={b.mes} style={bSel?.mes === b.mes ? { background: "var(--gana-soft)" } : undefined}>
|
||||
<td>
|
||||
{b.lbl}
|
||||
{b.enCurso ? <span style={{ color: "var(--tinta-suave)", fontSize: 11 }}> · en curso</span> : null}
|
||||
</td>
|
||||
<td className="num">{b.won}</td>
|
||||
<td className="num" style={escalaMag(b.sumW, rIng[0], rIng[1])}>
|
||||
{money(b.sumW)}
|
||||
</td>
|
||||
<td className="num" style={{ ...escalaMag(flojo ? null : b.mediana, rMed[0], rMed[1]), opacity: flojo ? 0.45 : 1 }} title={flojo ? `Solo ${b.won} cierres — por debajo de ${TEND_MIN_N} este número no es interpretable` : undefined}>
|
||||
{b.won ? money(b.mediana) : "—"}
|
||||
</td>
|
||||
<td className="num" style={{ opacity: flojo ? 0.45 : 1 }}>
|
||||
{b.won ? money(b.arpu) : "—"}
|
||||
</td>
|
||||
<td className="num" style={{ ...escalaMag(flojo ? null : b.convReal, rConv[0], rConv[1]), opacity: flojo ? 0.45 : 1 }}>
|
||||
{b.won ? (b.convReal == null ? "—" : `${b.convReal}%`) : "—"}
|
||||
</td>
|
||||
<td className="num" style={b.pctMayor >= 30 ? { color: "var(--alerta)", fontWeight: 700 } : undefined} title={b.pctMayor >= 30 ? "Una sola oportunidad concentra buena parte del ingreso de este período" : undefined}>
|
||||
{b.won ? `${b.pctMayor}%` : "—"}
|
||||
</td>
|
||||
<td className="num">{b.meta ? money(b.meta) : "—"}</td>
|
||||
<td className="num" style={escalaCumpl(b.cumpl)}>
|
||||
{b.cumpl == null ? "—" : `${b.cumpl}%`}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 18 }}>
|
||||
<WonTable rows={won} title={`Oportunidades ganadas — ${ambito}`} locked={scope.locked} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
4
app/tuberia/loading.js
Normal file
4
app/tuberia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue