Objetivos de actividad: agrega Reunión Técnica, Recopilación Proyecto SW, Retención y Cobro Factura (antes Postventa/Cobro); Next 16.4.6 por GHSA-vc7v-qv4w-wrv8
This commit is contained in:
commit
287ddce814
185 changed files with 19904 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 -->
|
||||
93
CLAUDE.md
Normal file
93
CLAUDE.md
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
@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.
|
||||
- **Rutina después de cada publicación (acordada con Marco el 2026-11-06):** correr `git fetch origin` y luego `git reset origin/main` (sin `--hard`). Mueve solo el historial local al de Forgejo y **no toca ningún archivo**, así el git no queda «adelante/atrás». Antes, comprobar que la carpeta coincide con `origin/main` (ignorando fin de línea: `git archive origin/main` a una carpeta temporal y `diff -rq --strip-trailing-cr`). Solo `git reset` **sin** `--hard`; `git pull` y `git checkout .` siguen prohibidos sin revisar.
|
||||
- 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.
|
||||
|
||||
## Gestionar actividades desde la app (2026-11-06)
|
||||
|
||||
Ventana emergente para **completar, reprogramar, cancelar y deshacer** citas, llamadas y tareas sin ir a Dynamics. Diseño y revisión EGM: `Proyectos/Análisis e Informes/Analitica de CRM/egm/concepts_brief.md`.
|
||||
|
||||
- **Código:** `app/components/actividades/GestionarActividad.js` (ventana; se abre desde la Agenda `/` y el Detalle de Plan de Actividades), `app/actividades/gestionActions.js` (acciones de servidor: abrir, ejecutar, deshacer, refrescar), `app/lib/actividadesServer.js` (Dynamics), `app/lib/actividadAcciones.js` (bitácora SQLite `actividad_accion`: actor, previo, nuevo).
|
||||
- **Estados (statecode/statuscode), verificados con escritura real:** llamada completada 1/2, cancelada 2/3; cita 1/3 y 2/4; tarea 1/5 y 2/6 (con `percentcomplete` 100). Deshacer reabre al estado previo y devuelve nota, fecha real y avance.
|
||||
- **Notas:** cita → `alfa_resultadodelavisita` (HTML, antepuesta). **Nunca** la descripción de la cita (es la invitación). Llamada y tarea → `description` (antepuesta).
|
||||
- **Reglas:** `If-Match` (etag) al escribir datos; citas con invitados (máscara 5 o 6) no se reprograman ni cancelan desde la app; cada ejecutivo solo toca lo suyo, el administrador y la asistente pueden actuar a nombre de otros (la ventana lo avisa).
|
||||
- **Refresco:** las pantallas se refrescan **al cerrar** la ventana (`refrescarPantallasAction`). Refrescar antes desmonta la ventana y se pierde «Deshacer». La Agenda es la ruta `/`.
|
||||
- **Interruptores de emergencia (variables de entorno en Coolify, sin publicar de nuevo):** `ACTIVIDADES_ACCIONES=off` deja la app solo de lectura; `PARTICIPANTES_OPP=off` completa igual pero no toca la oportunidad.
|
||||
- **Participantes:** al completar se marcan chips (`lib/participantes.js`: 100000000 Gerencia Comercial, …01 Preventa SmartWeb, …02 Preventa Seguridad, …03 Gerencia Operaciones, …04 Gerencia General). Se guardan en la cita (`alfa_participantes`, **antes** de cerrarla: una actividad cerrada es de solo lectura) y se **suman** a la oportunidad: Gerencia Comercial → Sí/No `alfa_participaciondegv` (alimenta la puntuación +5), los demás → `alfa_participantes`. Nunca quita ni baja un Sí a No. Si falla la oportunidad, la actividad queda completada y se avisa. Indicador en `/participacion`.
|
||||
- **Pruebas:** oportunidad «Oportunidad de prueba 2 - stageid» (cuenta EMPRESA ABC, propietario Marco). Crear actividades de prueba es seguro; Marco entra al Agendador por URL (`?owner=marco.montenegro@alfa.com.ni`) pero no aparece en la lista del filtro (solo los 5 ejecutivos); para ver sus actividades en local se agregó temporalmente su nombre a `EJECUTIVOS_VENTA` en `derive.js` (quitarlo antes de publicar).
|
||||
- **Lección:** al escribir regex con scripts de shell se pueden perder las `\` (el Agendador rechazó toda fecha por `/^d{4}-d{2}-d{2}$/`). Revisar el archivo después de escribirlo.
|
||||
|
||||
## Agendador: reglas y GV (2026-11-11)
|
||||
|
||||
- Reglas en `AGENDADOR` (`app/lib/agendador.js`): franjas 8:30–12:00 y 13:30–17:00; llamada 10 min (horas cada 10), visita 60 min (cada 30); máximos por día 10 llamadas, 4 visitas, 6 tareas; tareas vencen 16:00. También rigen el seguimiento al completar.
|
||||
- **«Con GV»**: ver `crearActividad` (`agendadorServer.js`) y `agendadorActions.js`. Cita con GV: `appointment_activity_parties` con organizador (7) y Marco (5, `GV_USUARIO` en `participantes.js`). Esas citas cuentan a Marco como «invitado», así que la ventana de gestión no las reprograma ni cancela (se hace en Dynamics).
|
||||
- Seguimiento al completar: un solo botón «Guardar, completar y programar seguimiento»; objetivo validado contra `OBJETIVOS_LIBRES`; el servidor rechaza sábados y domingos.
|
||||
|
||||
## Campanita y seguimiento del mismo día (2026-11-13)
|
||||
|
||||
- **Campanita** (barra superior, `app/components/Campanita.js`; datos en `app/api/campanita/route.js` + `app/lib/campanita.js`, que reutiliza `armarPlanPeriodo`/`listaPlana`): número rojo = vencidas del mes en curso (abiertas de días anteriores o de hoy con hora pasada) + llamadas/visitas que empiezan en ≤30 min. Ejecutivo: sus actividades. Administrador sin `?owner`: solo actividades con Gerencia Comercial, sin vencidas. El administrador puede pasar `?owner=correo` al endpoint para ver lo que vería ese ejecutivo (así se validó). `fresh=1` salta la caché de 4 min (se usa tras gestionar). Sin avisos push (va en la PWA, etapa 2).
|
||||
- **Seguimiento mismo día**: botón «Hoy, más tarde» en `GestionarActividad`; `horasLibres` (`agendador.js`) quita horas pasadas (margen 5 min) y las que chocan con lo ya agendado hoy (`hoyAgenda` de `abrirActividadAction`). El servidor sigue validando igual.
|
||||
|
||||
## App de campo (PWA) — rutas `/m/...` (2026-11-14)
|
||||
|
||||
Versión de teléfono de la misma app (mismo login, mismos permisos: `ownerFilter`/`authz`). **Las páginas web no cambian** (solo: `AppShell` cede el marco a `CampoShell` cuando la ruta empieza por `/m`, y muestra el aviso «Usar la versión de campo →» en ≤ 600 px).
|
||||
- **Pantallas:** `/m/hoy`, `/m/calendario`, `/m/semana`, `/m/tuberia`, `/m/cuentas`, `/m/cuentas/[id]`, `/m/oportunidad/[id]`. Marco/asistente eligen propietario con `OwnerM` (`?owner=`).
|
||||
- **Código:** `app/m/` (páginas, `components/`: `CampoShell`, `HojaActividad` = hoja de acciones, `NuevaMovil` = botón +, `BotonesContacto`, `WhatsAppRegistro`, `OppAcciones` = ✎ Editar y 📝 Nota), `lib/campo.js` (puro: WhatsApp/teléfono/mapas, categorías, opciones de campos), `lib/campoServer.js` (Dynamics), `lib/campoPagina.js`, `m/campoActions.js`. CSS propio: `public/assets/css/campo.css` (solo se carga en `/m`).
|
||||
- **Reutiliza**, sin duplicar reglas: `plan.js`, `agendaDia.js`, `agendador.js`, `participantes.js`, `queries.js`, acciones de `gestionActions.js` (completar/reprogramar/cancelar/seguimiento/editar/deshacer) y `cuentasActions.js` (alta con «Ya la realicé»; se le añadió el parámetro `canal`: `whatsapp` pone «WhatsApp – …» en el asunto).
|
||||
- **PWA:** `public/campo/manifest.webmanifest` (+ iconos a partir de `Logos A+ -01.png`), `public/campo-sw.js` (alcance **solo `/m/`**: copia de `/m/hoy` con sesión → «Sin conexión · actualizado HH:MM»; estáticos de Next; no guarda auth ni otras rutas; sin push). Cerrar sesión borra esa copia.
|
||||
- **Edición de oportunidad (✎):** PATCH con `If-Match`, solo lo que cambió; «Deshacer» 10 min (bitácora `actividad_accion`, acciones `edicion_opp`/`nota_opp`, canal `movil`). Editable: previsión, tipo (`alfa_typeopportunity`, **es un Choice, no un lookup**: no existe otro campo «tipo de oportunidad»), nivel de probabilidad (`alfa_niveldeprobabilidad`: Alta/Mediana/**Se desconoce**, no hay «Baja»), cierre, MRR, competidor (lookup `alfa_competidorid` → `competitors`), luz amarilla, participantes (GC → `alfa_participaciondegv`), estado de la negociación (memo ≤ 2000) + nota nativa opcional. Solo lectura: plan de cierre, clasificación (`alfa_clasificaciondeoportunidad`, el termómetro), línea de negocio. No se gana/pierde. Interruptor: `OPORTUNIDAD_EDICION=off`.
|
||||
- **Pendiente:** avisos push; probar el service worker en un teléfono real (el navegador integrado no registra SW); probar WhatsApp real.
|
||||
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"]
|
||||
348
app/actividades/gestionActions.js
Normal file
348
app/actividades/gestionActions.js
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "../lib/auth";
|
||||
import { esAsistente } from "../lib/authz";
|
||||
import { resolveOwnerId } from "../lib/queries";
|
||||
import { hoyManagua, esHabil } from "../lib/plan";
|
||||
import { TIPOS_AGENDADOR, OBJETIVOS_LIBRES, horaAMin, localDeIso, fechaMaxima, validar, resumenExistentes } from "../lib/agendador";
|
||||
import { objetivosPorNombre, actividadesFrescas, oportunidadesFrescas, crearActividad, cancelarActividad as cancelarAgendada } from "../lib/agendadorServer";
|
||||
import {
|
||||
leerActividad, problemaPara, fotoDe, completarActividad, cancelarActividad, reprogramarActividad, deshacerAccion,
|
||||
leerParticipacionOpp, sumarParticipacionOpp, notaLegible, editarActividad, deshacerEdicion,
|
||||
} from "../lib/actividadesServer";
|
||||
import { registrarAccion, getAccion, marcarAccionDeshecha } from "../lib/actividadAcciones";
|
||||
import { CODIGOS, nombresDe } from "../lib/participantes";
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const ACCIONES = ["completar", "reprogramar", "cancelar"];
|
||||
const MAX_NOTA = 1500;
|
||||
|
||||
// Interruptor de emergencia: con ACTIVIDADES_ACCIONES=off en el entorno, la app solo muestra las
|
||||
// actividades y no escribe nada en Dynamics (sin necesidad de publicar de nuevo).
|
||||
const apagado = () => String(process.env.ACTIVIDADES_ACCIONES || "").toLowerCase() === "off";
|
||||
|
||||
// Interruptor aparte para la participación que se suma a la oportunidad (afecta la puntuación): con
|
||||
// PARTICIPANTES_OPP=off la actividad se completa igual, pero no se toca la oportunidad.
|
||||
const oppApagado = () => String(process.env.PARTICIPANTES_OPP || "").toLowerCase() === "off";
|
||||
|
||||
// La Agenda es la página raíz («/»), por eso va en la lista.
|
||||
const refrescar = () => {
|
||||
["/", "/actividades", "/plan", "/prevision", "/agendador", "/tuberia", "/participacion", "/m/hoy", "/m/semana", "/m/calendario", "/m/tuberia"].forEach((p) => revalidatePath(p));
|
||||
};
|
||||
|
||||
const MENSAJES = {
|
||||
CERRADA: "Esta actividad ya está cerrada (completada o cancelada). Recarga la pantalla.",
|
||||
CON_INVITADOS: "Esta cita tiene invitados. Para no enviarles avisos por error, reprográmala o cancélala directamente en Dynamics.",
|
||||
};
|
||||
|
||||
// Traduce los errores de Dynamics a algo que el ejecutivo pueda entender y accionar.
|
||||
function errorDe(e, contexto = {}) {
|
||||
const m = String(e?.message || e);
|
||||
console.error("[actividades]", JSON.stringify({ ...contexto, error: m.slice(0, 400) }));
|
||||
if (m === "TOKEN_EXPIRED") return "Tu sesión expiró. Vuelve a iniciar sesión y reintenta (lo que escribiste en la nota se conserva en esta ventana).";
|
||||
if (m.includes("DATAVERSE_403")) return "Dynamics no te permite modificar esta actividad. Si es de otro ejecutivo, pídele que la gestione o hazlo en Dynamics.";
|
||||
if (m.includes("DATAVERSE_404")) return "No encontré la actividad en Dynamics (¿la eliminaron?). Recarga la pantalla.";
|
||||
if (m.includes("DATAVERSE_412")) return "Alguien cambió esta actividad mientras la tenías abierta. Cierra esta ventana, ábrela de nuevo y reintenta.";
|
||||
if (m.includes("DATAVERSE_429")) return "Dynamics está ocupado. Espera unos segundos y reintenta.";
|
||||
const codigo = m.match(/DATAVERSE_(\d+)/)?.[1];
|
||||
return `No se pudo completar la operación en Dynamics${codigo ? ` (código ${codigo})` : ""}. Intenta de nuevo; si persiste, avisa a Marco.`;
|
||||
}
|
||||
|
||||
// ¿Puede esta sesión tocar una actividad de `ownerId`? El propio ejecutivo; el administrador y la asistente
|
||||
// de ventas pueden hacerlo a nombre de otros (Dynamics igual aplica los permisos de quien actúa).
|
||||
async function puedeTocar(session, ownerId) {
|
||||
const mio = await resolveOwnerId(session.email, session.accessToken);
|
||||
const esMia = !!mio && mio === ownerId;
|
||||
if (session.isAdmin || esAsistente(session.email)) return { ok: true, enNombreDeOtro: !esMia };
|
||||
return esMia ? { ok: true, enNombreDeOtro: false } : { ok: false };
|
||||
}
|
||||
|
||||
// El refresco de las pantallas se hace AL CERRAR la ventana, no al ejecutar: si se refrescara antes, la
|
||||
// actividad (ya completada) desaparecería de la lista y se llevaría la ventana con el botón «Deshacer».
|
||||
export async function refrescarPantallasAction() {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false };
|
||||
refrescar();
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const datosPublicos = (act, { hoy, puede }) => ({
|
||||
id: act.id,
|
||||
tipo: act.tipo,
|
||||
etag: act.etag,
|
||||
asunto: act.asunto,
|
||||
estado: act.estado,
|
||||
scheduledstart: act.scheduledstart,
|
||||
scheduledend: act.scheduledend,
|
||||
owner: act.owner,
|
||||
referente: act.referente,
|
||||
invitados: act.invitados,
|
||||
tieneNota: !!(act.tipo === "Cita" ? act.resultadoVisita : act.description),
|
||||
hoy,
|
||||
enNombreDeOtro: puede.enNombreDeOtro,
|
||||
objetivo: act.objetivo,
|
||||
nota: notaLegible(act),
|
||||
lugar: act.lugar || null,
|
||||
duracion: act.scheduledstart && act.scheduledend ? Math.round((new Date(act.scheduledend) - new Date(act.scheduledstart)) / 60000) : null,
|
||||
});
|
||||
|
||||
// Abre una actividad: la vuelve a leer en Dynamics (datos de este momento) y dice qué se puede hacer.
|
||||
export async function abrirActividadAction({ tipo, id }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (!TIPOS_AGENDADOR.includes(tipo) || !UUID.test(String(id || ""))) return { ok: false, error: "Actividad no válida." };
|
||||
try {
|
||||
const act = await leerActividad(session.accessToken, tipo, id);
|
||||
const puede = await puedeTocar(session, act.ownerId);
|
||||
if (!puede.ok) return { ok: false, error: "Solo puedes gestionar tus propias actividades." };
|
||||
const pub = datosPublicos(act, { hoy: hoyManagua(), puede });
|
||||
// Lo que ya está registrado en la oportunidad (para mostrarlo y no pedirlo dos veces).
|
||||
let opp = null;
|
||||
if (act.oppId) {
|
||||
try {
|
||||
const o = await leerParticipacionOpp(session.accessToken, act.oppId);
|
||||
opp = { gv: o.gv, participantes: o.participantes };
|
||||
} catch { /* sin dato: el modal funciona igual */ }
|
||||
}
|
||||
// Lo ya agendado HOY por el dueño de la actividad: con eso la ventana quita las horas que chocarían al
|
||||
// programar un seguimiento «hoy, más tarde». Si falla, la ventana solo quita las horas pasadas y el servidor valida.
|
||||
let hoyAgenda = null;
|
||||
if (act.oppId) {
|
||||
try {
|
||||
const acts = await actividadesFrescas(session.accessToken, act.ownerId, pub.hoy, pub.hoy);
|
||||
const r = resumenExistentes(acts);
|
||||
hoyAgenda = { bloques: r.bloques[pub.hoy] || [], cuenta: r.existentes[pub.hoy] || { Llamada: 0, Cita: 0, Tarea: 0 } };
|
||||
} catch { /* sin dato */ }
|
||||
}
|
||||
return { ok: true, apagado: apagado(), actividad: { ...pub, participantes: act.participantes, tieneOpp: !!act.oppId, opp, hoyAgenda } };
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e, { paso: "abrir", tipo, id }) };
|
||||
}
|
||||
}
|
||||
|
||||
// Completar, reprogramar o cancelar. El navegador solo dice QUÉ quiere; permisos, estado, fechas y
|
||||
// concurrencia se verifican AQUÍ con datos de este momento.
|
||||
export async function ejecutarAccionAction({ tipo, id, accion, nota, dia, hora, participantes }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento. Intenta más tarde o hazlo en Dynamics." };
|
||||
if (!TIPOS_AGENDADOR.includes(tipo) || !UUID.test(String(id || "")) || !ACCIONES.includes(accion)) return { ok: false, error: "Solicitud no válida." };
|
||||
const texto = String(nota || "").slice(0, MAX_NOTA);
|
||||
|
||||
const hoy = hoyManagua();
|
||||
if (accion === "reprogramar") {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(dia || "")) || dia < hoy || dia > fechaMaxima(hoy)) {
|
||||
return { ok: false, error: "La nueva fecha debe estar entre hoy y los próximos 30 días." };
|
||||
}
|
||||
if (tipo !== "Tarea") {
|
||||
const m = horaAMin(String(hora || ""));
|
||||
if (m == null || m < 360 || m > 1200) return { ok: false, error: "Elige una hora entre 6:00 y 20:00." };
|
||||
if (dia === hoy && m < localDeIso(new Date().toISOString()).min) return { ok: false, error: "Esa hora ya pasó." };
|
||||
}
|
||||
}
|
||||
|
||||
const ctx = { actor: session.email, tipo, id, accion };
|
||||
try {
|
||||
const token = session.accessToken;
|
||||
const act = await leerActividad(token, tipo, id);
|
||||
const puede = await puedeTocar(session, act.ownerId);
|
||||
if (!puede.ok) return { ok: false, error: "Solo puedes gestionar tus propias actividades." };
|
||||
const prob = problemaPara(act, accion);
|
||||
if (prob) return { ok: false, error: MENSAJES[prob] };
|
||||
|
||||
const previo = fotoDe(act);
|
||||
let nuevo;
|
||||
let opp = null;
|
||||
let avisoOpp = null;
|
||||
if (accion === "completar") {
|
||||
const roles = (Array.isArray(participantes) ? participantes : []).map(String).filter((c) => CODIGOS.includes(c));
|
||||
nuevo = await completarActividad(token, act, texto, roles);
|
||||
if ((act.tipo === "Cita" || act.tipo === "Llamada") && roles.length) nuevo.escribioParticipantes = true;
|
||||
// La actividad ya quedó completada. Sumar la participación a la oportunidad es un segundo paso que
|
||||
// puede fallar SIN deshacer el cierre: en ese caso solo se avisa.
|
||||
if (roles.length && act.oppId && !oppApagado()) {
|
||||
try {
|
||||
opp = await sumarParticipacionOpp(token, act.oppId, roles);
|
||||
if (opp.cambio) {
|
||||
previo.opp = opp.previo;
|
||||
nuevo.opp = opp.nuevo;
|
||||
}
|
||||
} catch (e) {
|
||||
avisoOpp = "La actividad se completó, pero no pude actualizar la participación en la oportunidad. Puedes marcarla en Dynamics.";
|
||||
console.error("[actividades]", JSON.stringify({ paso: "participacion_opp", actor: session.email, id, error: String(e?.message || e).slice(0, 300) }));
|
||||
}
|
||||
} else if (roles.length && !act.oppId) {
|
||||
avisoOpp = "La actividad no está ligada a una oportunidad: la participación no se registró en ninguna.";
|
||||
}
|
||||
} else if (accion === "cancelar") nuevo = await cancelarActividad(token, act, texto);
|
||||
else nuevo = await reprogramarActividad(token, act, dia, hora);
|
||||
|
||||
const accionId = registrarAccion({
|
||||
actor: session.email, ownerId: act.ownerId, ownerName: act.owner, tipo, activityId: id, accion, resultado: "ok", previo, nuevo,
|
||||
});
|
||||
// Resumen para mostrar: qué cambió en la oportunidad.
|
||||
const resumenOpp = opp?.cambio
|
||||
? {
|
||||
roles: nombresDe(opp.nuevo.participantes.filter((c) => !opp.previo.participantes.includes(c))),
|
||||
marcoGV: opp.nuevo.gv && !opp.previo.gv,
|
||||
}
|
||||
: opp && !opp.cambio
|
||||
? { yaEstaba: true }
|
||||
: null;
|
||||
return { ok: true, accionId, accion, enNombreDeOtro: puede.enNombreDeOtro, owner: act.owner, nuevo, opp: resumenOpp, avisoOpp };
|
||||
} catch (e) {
|
||||
try {
|
||||
registrarAccion({ actor: session.email, tipo, activityId: id, accion, resultado: "error", error: e?.message });
|
||||
} catch { /* la bitácora nunca debe ocultar el error real */ }
|
||||
return { ok: false, error: errorDe(e, ctx) };
|
||||
}
|
||||
}
|
||||
|
||||
// «Deshacer» la última acción: reabre (vuelve al estado previo) o devuelve la fecha anterior.
|
||||
export async function deshacerAccionAction(accionId) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento." };
|
||||
const reg = getAccion(Number(accionId));
|
||||
if (!reg || reg.resultado !== "ok") return { ok: false, error: "No encontré esa acción." };
|
||||
if (reg.deshecho_en) return { ok: false, error: "Esa acción ya se deshizo." };
|
||||
try {
|
||||
const puede = await puedeTocar(session, reg.owner_id);
|
||||
if (!puede.ok) return { ok: false, error: "No tienes permiso para deshacer esta acción." };
|
||||
const r = await deshacerAccion(session.accessToken, reg.tipo, reg.activity_id, reg.accion, reg.previo, reg.nuevo);
|
||||
if (r === "CAMBIO") return { ok: false, error: "La actividad cambió después de tu acción; ya no se puede deshacer desde aquí." };
|
||||
marcarAccionDeshecha(reg.id, session.email);
|
||||
return { ok: true, sinNota: r === "ok_sin_nota" };
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e, { paso: "deshacer", accionId }) };
|
||||
}
|
||||
}
|
||||
|
||||
// Programa la SIGUIENTE actividad de seguimiento justo después de completar otra (misma oportunidad, mismo
|
||||
// propietario). Reutiliza las reglas del Agendador (horario, máximos por día, sin encimar) y se registra en la
|
||||
// bitácora para poder deshacerla (cancela la nueva; nunca borra).
|
||||
export async function crearSeguimientoAction({ tipo, id, nuevoTipo, objetivo, dia, hora }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento." };
|
||||
if (!TIPOS_AGENDADOR.includes(tipo) || !TIPOS_AGENDADOR.includes(nuevoTipo) || !UUID.test(String(id || ""))) return { ok: false, error: "Solicitud no válida." };
|
||||
if (!OBJETIVOS_LIBRES.includes(String(objetivo || ""))) return { ok: false, error: "Elige un objetivo." };
|
||||
const hoy = hoyManagua();
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(dia || "")) || dia < hoy || dia > fechaMaxima(hoy)) {
|
||||
return { ok: false, error: "La fecha debe estar entre hoy y los próximos 30 días." };
|
||||
}
|
||||
// El seguimiento sigue el mismo horario del Agendador: de lunes a viernes (sábados y domingos no).
|
||||
if (!esHabil(dia)) return { ok: false, error: "Elige un día hábil: el seguimiento no se agenda en sábado ni en domingo." };
|
||||
try {
|
||||
const token = session.accessToken;
|
||||
const origen = await leerActividad(token, tipo, id);
|
||||
const puede = await puedeTocar(session, origen.ownerId);
|
||||
if (!puede.ok) return { ok: false, error: "Solo puedes gestionar tus propias actividades." };
|
||||
if (!origen.oppId) return { ok: false, error: "La actividad no está ligada a una oportunidad; el seguimiento se agenda desde el Agendador o en Dynamics." };
|
||||
const [opps, objetivos, acts] = await Promise.all([
|
||||
oportunidadesFrescas(token, [origen.oppId]),
|
||||
objetivosPorNombre(token),
|
||||
actividadesFrescas(token, origen.ownerId, dia, dia),
|
||||
]);
|
||||
const opp = opps.get(origen.oppId);
|
||||
if (!opp || !opp.abierta) return { ok: false, error: "La oportunidad ya no está abierta." };
|
||||
const objetivoId = objetivos.get(objetivo);
|
||||
if (!objetivoId) return { ok: false, error: "No encontré ese objetivo en Dynamics." };
|
||||
const it = { key: origen.oppId, oppId: origen.oppId, nombre: opp.nombre, cliente: null, tipo: nuevoTipo, objetivo, dia, hora: nuevoTipo === "Tarea" ? "" : String(hora || "") };
|
||||
const { existentes, bloques } = resumenExistentes(acts);
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||||
// El seguimiento acepta los objetivos «libres» (incluye «Prospección», que el ejecutivo trae de la actividad original);
|
||||
// el Agendador masivo sigue limitado a OBJETIVOS_AGENDADOR.
|
||||
const v = validar({ items: [it], dias: [dia], existentes, bloques, hoy, ahoraMin, objetivos: OBJETIVOS_LIBRES });
|
||||
if (!v.ok) return { ok: false, error: (v.porItem[it.key] || []).join(" ") };
|
||||
const nuevoId = await crearActividad(token, it, opp, origen.ownerId, objetivoId, session.email);
|
||||
const accionId = registrarAccion({
|
||||
actor: session.email, ownerId: origen.ownerId, ownerName: origen.owner, tipo: nuevoTipo, activityId: nuevoId, accion: "seguimiento", resultado: "ok",
|
||||
previo: { origenId: id, origenTipo: tipo }, nuevo: { dia, hora: it.hora, objetivo },
|
||||
});
|
||||
return { ok: true, accionId, tipo: nuevoTipo, dia, hora: it.hora };
|
||||
} catch (e) {
|
||||
try { registrarAccion({ actor: session.email, tipo: nuevoTipo, activityId: id, accion: "seguimiento", resultado: "error", error: e?.message }); } catch { /* ignorar */ }
|
||||
return { ok: false, error: errorDe(e, { paso: "seguimiento", tipo, id }) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deshacerSeguimientoAction(accionId) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
const reg = getAccion(Number(accionId));
|
||||
if (!reg || !["seguimiento", "creacion"].includes(reg.accion) || reg.resultado !== "ok") return { ok: false, error: "No encontré esa acción." };
|
||||
if (reg.deshecho_en) return { ok: false, error: "Ese seguimiento ya se deshizo." };
|
||||
try {
|
||||
const puede = await puedeTocar(session, reg.owner_id);
|
||||
if (!puede.ok) return { ok: false, error: "No tienes permiso para deshacer esta acción." };
|
||||
await cancelarAgendada(session.accessToken, reg.tipo, reg.activity_id);
|
||||
marcarAccionDeshecha(reg.id, session.email);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e, { paso: "deshacer_seguimiento", accionId }) };
|
||||
}
|
||||
}
|
||||
|
||||
const DURACIONES = { Llamada: [10, 15, 30, 45, 60], Cita: [30, 60, 90, 120] };
|
||||
|
||||
// Edita una actividad abierta sin completarla (objetivo, duración, nota previa, participantes de la visita). No toca
|
||||
// asunto, descripción ni invitados. Cambiar la duración de una visita con invitados se hace en Dynamics (avisaría a los
|
||||
// invitados). Se registra en la bitácora y se puede deshacer.
|
||||
export async function editarActividadAction({ tipo, id, objetivo, duracion, nota, participantes }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento. Intenta más tarde o hazlo en Dynamics." };
|
||||
if (!TIPOS_AGENDADOR.includes(tipo) || !UUID.test(String(id || ""))) return { ok: false, error: "Solicitud no válida." };
|
||||
if (objetivo && !OBJETIVOS_LIBRES.includes(String(objetivo))) return { ok: false, error: "Objetivo no permitido." };
|
||||
const dur = duracion ? Number(duracion) : null;
|
||||
if (dur && !(DURACIONES[tipo] || []).includes(dur)) return { ok: false, error: "Duración no válida." };
|
||||
const roles = Array.isArray(participantes) ? participantes.map(String).filter((c) => CODIGOS.includes(c)) : null;
|
||||
const ctx = { actor: session.email, tipo, id, accion: "editar" };
|
||||
try {
|
||||
const token = session.accessToken;
|
||||
const act = await leerActividad(token, tipo, id);
|
||||
const puede = await puedeTocar(session, act.ownerId);
|
||||
if (!puede.ok) return { ok: false, error: "Solo puedes gestionar tus propias actividades." };
|
||||
if (act.estado !== "abierta") return { ok: false, error: MENSAJES.CERRADA };
|
||||
if (dur && tipo === "Cita" && act.invitados > 0) {
|
||||
const igual = act.scheduledstart && act.scheduledend && Math.round((new Date(act.scheduledend) - new Date(act.scheduledstart)) / 60000) === dur;
|
||||
if (!igual) return { ok: false, error: "Esta visita tiene invitados: cambia su duración directamente en Dynamics para no enviarles avisos por error." };
|
||||
}
|
||||
let objetivoId = null;
|
||||
if (objetivo) {
|
||||
objetivoId = (await objetivosPorNombre(token)).get(objetivo) || null;
|
||||
if (!objetivoId) return { ok: false, error: "No encontré ese objetivo en Dynamics." };
|
||||
}
|
||||
const r = await editarActividad(token, act, { objetivoId, duracionMin: dur, nota: String(nota || "").slice(0, MAX_NOTA), participantes: tipo === "Cita" || tipo === "Llamada" ? roles : null });
|
||||
if (!r) return { ok: false, error: "No hay cambios que guardar." };
|
||||
const accionId = registrarAccion({
|
||||
actor: session.email, ownerId: act.ownerId, ownerName: act.owner, tipo, activityId: id, accion: "edicion", resultado: "ok", previo: r.previo, nuevo: r.nuevo,
|
||||
});
|
||||
return { ok: true, accionId, accion: "editar", enNombreDeOtro: puede.enNombreDeOtro, owner: act.owner };
|
||||
} catch (e) {
|
||||
try {
|
||||
registrarAccion({ actor: session.email, tipo, activityId: id, accion: "edicion", resultado: "error", error: e?.message });
|
||||
} catch { /* la bitácora nunca debe ocultar el error real */ }
|
||||
return { ok: false, error: errorDe(e, ctx) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function deshacerEdicionAction(accionId) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento." };
|
||||
const reg = getAccion(Number(accionId));
|
||||
if (!reg || reg.accion !== "edicion" || reg.resultado !== "ok") return { ok: false, error: "No encontré esa acción." };
|
||||
if (reg.deshecho_en) return { ok: false, error: "Esa edición ya se deshizo." };
|
||||
try {
|
||||
const puede = await puedeTocar(session, reg.owner_id);
|
||||
if (!puede.ok) return { ok: false, error: "No tienes permiso para deshacer esta acción." };
|
||||
const r = await deshacerEdicion(session.accessToken, reg.tipo, reg.activity_id, reg.previo || {}, reg.nuevo || {});
|
||||
if (r === "CAMBIO") return { ok: false, error: "La actividad ya no está abierta; no se puede deshacer desde aquí." };
|
||||
marcarAccionDeshecha(reg.id, session.email);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: errorDe(e, { paso: "deshacer_edicion", accionId }) };
|
||||
}
|
||||
}
|
||||
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 />;
|
||||
}
|
||||
282
app/actividades/page.js
Normal file
282
app/actividades/page.js
Normal file
|
|
@ -0,0 +1,282 @@
|
|||
import { Suspense } from "react";
|
||||
import Link from "next/link";
|
||||
import { auth } from "../lib/auth";
|
||||
import { ownerFilter, puedeAgendarPara } from "../lib/authz";
|
||||
import { getActividades, getSystemUsers, getOportunidadesSemana } from "../lib/queries";
|
||||
import { AGENDADOR, localDeIso } from "../lib/agendador";
|
||||
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import {
|
||||
armarPlanPeriodo, sinActividadPeriodo, hoyManagua, addDays, semanaDe, diasDelRango, esHabil, diaSemana,
|
||||
PERIODOS_ACT, periodoActActivo, rangoPeriodoAct,
|
||||
} from "../lib/plan";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import PeriodoControles from "../components/plan/PeriodoControles";
|
||||
import PlanSeccionPeriodo from "../components/plan/PlanSeccionPeriodo";
|
||||
import PlanTarjetasPeriodo from "../components/plan/PlanTarjetasPeriodo";
|
||||
import BarraSecciones from "../components/plan/BarraSecciones";
|
||||
import SinActividadPanel from "../components/plan/SinActividadPanel";
|
||||
import { gcDe } from "../lib/gerencia";
|
||||
import { actsDeSeccion, casillasSecciones, conteoTipos } from "../lib/planDia";
|
||||
import { listaPlana, marcarCruces } from "../lib/agendaDia";
|
||||
import AgendaCronologica from "../components/plan/AgendaCronologica";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
||||
const fechaCorta = (iso) => iso.split("-").reverse().slice(0, 2).join("/");
|
||||
|
||||
// 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>
|
||||
);
|
||||
}
|
||||
|
||||
// Enlace al resumen por ejecutivo de /equipo, con el mismo período (semana pasada/esta/próxima, mes pasado/este).
|
||||
function hrefEquipo(periodo) {
|
||||
const vista = periodo.startsWith("mes") ? "mes" : "semana";
|
||||
const off = periodo.endsWith("pasada") ? -1 : periodo.endsWith("proxima") ? 1 : 0;
|
||||
const p = new URLSearchParams();
|
||||
if (vista === "mes") p.set("vista", "mes");
|
||||
if (off) p.set("off", String(off));
|
||||
return `/equipo${p.toString() ? `?${p.toString()}` : ""}`;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// El agendador ahora es una página aparte (/agendador); aquí solo se ofrece el acceso.
|
||||
const ownerAgenda = scope.emails.length === 1 ? scope.emails[0] : null;
|
||||
const puedeAgendar = !!ownerAgenda && puedeAgendarPara(session, ownerAgenda);
|
||||
|
||||
let raw, allUsers, oppsPeriodo;
|
||||
try {
|
||||
[raw, allUsers, oppsPeriodo] = await Promise.all([
|
||||
getActividades(session.accessToken, scope),
|
||||
session.isAdmin || scope.asistente ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||
// Solo las que cierran dentro del período (lista «por planificar»).
|
||||
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 planCompleto = armarPlanPeriodo(raw, desde, hasta, hoy); // sin filtrar: lo usan las tarjetas y la franja
|
||||
const r = planCompleto.resumen;
|
||||
const actsDelPlan = planCompleto.secciones.flatMap((s) => s.filas.flatMap((fila) => fila.acts));
|
||||
|
||||
// Filtros combinables (intersección): «solo Gerencia Comercial» (?gc=1) y «solo vencidas» (?venc=1).
|
||||
// Trabajan sobre una copia: `planCompleto` no se muta. Vencida = fila con al menos una actividad abierta cuyo día ya pasó.
|
||||
const soloGC = sp.gc === "1";
|
||||
const soloVenc = sp.venc === "1";
|
||||
const plan =
|
||||
soloGC || soloVenc
|
||||
? {
|
||||
...planCompleto,
|
||||
secciones: planCompleto.secciones.map((s) => {
|
||||
const filas = s.filas.filter((fila) => (!soloGC || fila.acts.some((a) => gcDe(a))) && (!soloVenc || fila.vencidas > 0));
|
||||
return { ...s, filas, subtotal: filas.reduce((t, fila) => t + (fila.opp.valor || 0), 0) };
|
||||
}),
|
||||
}
|
||||
: planCompleto;
|
||||
// Cada enlace alterna su filtro y conserva los demás parámetros (owner, periodo y el otro filtro).
|
||||
const hrefFiltro = (clave, activo) => {
|
||||
const qs = new URLSearchParams(Object.entries(sp).filter(([k, v]) => k !== clave && typeof v === "string"));
|
||||
if (!activo) qs.set(clave, "1");
|
||||
return `/actividades${qs.toString() ? `?${qs.toString()}` : ""}`;
|
||||
};
|
||||
const hrefGC = hrefFiltro("gc", soloGC);
|
||||
const hrefVenc = hrefFiltro("venc", soloVenc);
|
||||
|
||||
// Tarjetas: sobre el plan sin filtrar (no cambian al activar un filtro). Barra y secciones: sobre el filtrado.
|
||||
const actTotalPeriodo = planCompleto.secciones.reduce((t, s) => t + actsDeSeccion(s), 0);
|
||||
const mrrPeriodo = planCompleto.secciones.reduce((t, s) => t + (s.subtotal || 0), 0);
|
||||
const tiposPeriodo = conteoTipos(planCompleto.secciones);
|
||||
const casillas = casillasSecciones(plan.secciones);
|
||||
|
||||
const sinActividad = esActualOFuturo
|
||||
? sinActividadPeriodo(
|
||||
scope.emails?.length ? oppsPeriodo : oppsPeriodo.filter((o) => EJECUTIVOS_VENTA.includes(o.owner)),
|
||||
raw,
|
||||
desde,
|
||||
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";
|
||||
// Varios ejecutivos a la vez: la tabla muestra la columna Ejecutivo y el gerente tiene el resumen en /equipo.
|
||||
const verVarios = !scope.locked && scope.emails.length !== 1 && owners.length > 0;
|
||||
const conEjecutivo = scope.emails.length !== 1;
|
||||
|
||||
// Vista cronológica (solo pantalla), agrupada por día. Los cruces se calculan sobre todas las actividades del período;
|
||||
// los filtros ?gc=1 y ?venc=1 (a nivel de fila, como siempre) solo quitan filas de la tabla.
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||||
const itemsTodos = marcarCruces(listaPlana(planCompleto.secciones, { hoy, ahoraMin, porHora: false }));
|
||||
const items = itemsTodos.filter((it) => (!soloGC || it.filaGC) && (!soloVenc || it.filaVencidas > 0));
|
||||
|
||||
return (
|
||||
<div className="plan-act" 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}`}
|
||||
/>
|
||||
</div>
|
||||
</Suspense>
|
||||
|
||||
{verVarios && session.isAdmin && (
|
||||
<p className="no-print pa-equipo-link">
|
||||
<Link href={hrefEquipo(periodo)}>Ver el resumen por ejecutivo en Equipo →</Link>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<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>
|
||||
|
||||
<PlanTarjetasPeriodo
|
||||
actTotal={actTotalPeriodo}
|
||||
tipos={tiposPeriodo}
|
||||
mrr={mrrPeriodo}
|
||||
actsGC={actsDelPlan}
|
||||
hrefGC={hrefGC}
|
||||
filtradoGC={soloGC}
|
||||
r={r}
|
||||
hrefVenc={hrefVenc}
|
||||
filtradoVenc={soloVenc}
|
||||
/>
|
||||
|
||||
<Franja rango={rango} plan={planCompleto} hoy={hoy} owner={sp.owner} />
|
||||
|
||||
{/* Pantalla: una sola tabla cronológica agrupada por día (una fila por actividad). */}
|
||||
<AgendaCronologica
|
||||
items={items}
|
||||
agruparPor="dia"
|
||||
colEjecutivo={conEjecutivo}
|
||||
modo="periodo"
|
||||
ahora={{ dia: hoy, min: ahoraMin }}
|
||||
hoy={hoy}
|
||||
/>
|
||||
|
||||
{/* PDF: sigue por objetivo, igual que siempre (en pantalla va oculto). */}
|
||||
<div className="vista-impresion">
|
||||
<BarraSecciones casillas={casillas} />
|
||||
|
||||
{plan.secciones.map((s) => (
|
||||
<PlanSeccionPeriodo key={s.key} seccion={s} conEjecutivo={conEjecutivo} hoy={hoy} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{puedeAgendar && (
|
||||
<section className="panel plan-agd no-print">
|
||||
<div className="agd-ayuda">
|
||||
<p>
|
||||
<b>Agendador de actividades:</b> ahora es un módulo aparte, con calendario de hasta 30 días, buscador y prioridad sugerida.{" "}
|
||||
<Link href={`/agendador?owner=${ownerAgenda}`}>Abrir el agendador de {quien} →</Link>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{esActualOFuturo && (
|
||||
<SinActividadPanel
|
||||
filas={sinActividad}
|
||||
titulo="Oportunidades por planificar: cierre estimado en el período y sin actividad agendada"
|
||||
hint={`Cierre entre el ${fechaCorta(desde)} y el ${fechaCorta(hasta)} · cuenta cualquier actividad del período, pendiente o completada · solo en pantalla`}
|
||||
vacio="Todas las oportunidades con cierre en este período tienen al menos una actividad agendada."
|
||||
/>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
106
app/admin/uso/page.js
Normal file
106
app/admin/uso/page.js
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import Link from "next/link";
|
||||
import { auth } from "../../lib/auth";
|
||||
import { resumenUso, accionesPorPersona } from "../../lib/uso";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const PERIODOS = { 7: "Últimos 7 días", 14: "Últimos 14 días", 30: "Últimos 30 días" };
|
||||
const NOMBRE_RUTA = {
|
||||
"/": "Calendario", "/plan": "Plan del Día", "/actividades": "Plan de Actividades", "/agendador": "Agendador", "/cuentas": "Cuentas (búsqueda)",
|
||||
"/cuentas/ficha": "Cuentas (ficha)", "/prevision": "Previsión de Ventas", "/tuberia": "Tubería de Ventas", "/resumen": "Ventas Resumen", "/ganadas": "Oportunidades Ganadas",
|
||||
"/perdemos": "Oportunidades Perdidas", "/tendencia": "Tendencia", "/renovaciones/prevision": "Previsión de Renovaciones", "/renovaciones/tuberia": "Tubería de Renovaciones",
|
||||
"/renovaciones/logradas": "Renovaciones Logradas", "/renovaciones/perdidas": "Renovaciones Perdidas", "/nuevas": "Cohorte / Oportunidades nuevas", "/participacion": "Participación de Gerencia",
|
||||
"/detalle": "Detalle", "/admin/metas": "Metas", "/admin/uso": "Uso de la app", "/equipo": "Equipo (gerente)",
|
||||
};
|
||||
const nom = (r) => NOMBRE_RUTA[r] || r;
|
||||
const fechaHora = (iso) => (iso ? new Date(new Date(iso).getTime() - 6 * 3600 * 1000).toISOString().replace("T", " ").slice(0, 16) : "—");
|
||||
|
||||
// Uso de la app por página y por persona (solo administradores). Mide VISITAS a páginas: no mide tiempo ni
|
||||
// lo que se hace dentro de cada página. Se complementa con las acciones sobre actividades (bitácora).
|
||||
export default async function UsoPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
if (!session.isAdmin) return <div style={{ padding: 24 }}><h2>Uso de la app</h2><p>Esta página es solo para administradores.</p></div>;
|
||||
|
||||
const sp = await searchParams;
|
||||
const dias = PERIODOS[sp.dias] ? Number(sp.dias) : 14;
|
||||
const u = resumenUso(dias);
|
||||
const acc = accionesPorPersona(dias);
|
||||
const accPor = {};
|
||||
acc.forEach((a) => { (accPor[a.email] ||= {})[a.accion] = a.n; });
|
||||
const topPor = {};
|
||||
u.rutasPorPersona.forEach((r) => { (topPor[r.email] ||= []).length < 3 && topPor[r.email].push(`${nom(r.ruta)} (${r.n})`); });
|
||||
const rutasPorRol = {};
|
||||
u.porRol.forEach((r) => { (rutasPorRol[r.ruta] ||= {})[r.rol] = r.n; });
|
||||
const personasEsperadas = 7;
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Uso de la app</h2>
|
||||
<p className="hint">
|
||||
Cada fila es una visita a una página (cambio de ruta); las recargas en menos de 20 segundos no cuentan. Mide qué páginas se abren y quién, no el tiempo ni lo que se hace
|
||||
dentro. {u.total.n ? `Hay datos desde el ${u.total.desde}.` : "Todavía no hay datos: el registro empieza con la primera visita tras publicar."}
|
||||
</p>
|
||||
<div className="seg-tabs" style={{ marginBottom: 14 }}>
|
||||
{Object.entries(PERIODOS).map(([k, l]) => (
|
||||
<Link key={k} href={`/admin/uso?dias=${k}`} className={dias === Number(k) ? "on" : ""} style={{ textDecoration: "none" }}>{l}</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{u.porRuta.reduce((a, r) => a + r.visitas, 0)}</span><span className="l">Visitas en el periodo</span></div>
|
||||
<div className="kpi"><span className="n">{u.porPersona.length}</span><span className="l">Personas que entraron (de {personasEsperadas} usuarios previstos)</span></div>
|
||||
<div className="kpi"><span className="n">{u.porRuta.length}</span><span className="l">Páginas distintas abiertas</span></div>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Por página</h3>
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Página</th><th className="num">Visitas</th><th className="num">Personas</th><th className="num">Días con uso</th><th>Ejecutivos</th><th>Asistente</th><th>Gerente</th></tr></thead>
|
||||
<tbody>
|
||||
{u.porRuta.map((r) => (
|
||||
<tr key={r.ruta}>
|
||||
<td>{nom(r.ruta)}</td><td className="num">{r.visitas}</td><td className="num">{r.personas}</td><td className="num">{r.dias_con_uso}</td>
|
||||
<td className="num">{rutasPorRol[r.ruta]?.ejecutivo || 0}</td><td className="num">{rutasPorRol[r.ruta]?.asistente || 0}</td><td className="num">{rutasPorRol[r.ruta]?.gerente || 0}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!u.porRuta.length && <tr><td colSpan={7}>Sin visitas registradas en este periodo.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Por persona</h3>
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Persona</th><th>Rol</th><th className="num">Visitas</th><th className="num">Días activos</th><th className="num">Páginas</th><th>Más visitadas</th><th>Última visita</th><th>Actividades (en la app)</th></tr></thead>
|
||||
<tbody>
|
||||
{u.porPersona.map((p) => {
|
||||
const a = accPor[p.email] || {};
|
||||
const txt = Object.entries(a).map(([k, n]) => `${n} ${k}`).join(", ");
|
||||
return (
|
||||
<tr key={p.email}>
|
||||
<td>{p.email}</td><td>{p.rol}</td><td className="num">{p.visitas}</td><td className="num">{p.dias_activos}</td><td className="num">{p.paginas}</td>
|
||||
<td>{(topPor[p.email] || []).join(", ")}</td><td>{fechaHora(p.ultima)}</td><td>{txt || "—"}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
{!u.porPersona.length && <tr><td colSpan={8}>Sin visitas registradas en este periodo.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Primera página que abre cada persona cada día</h3>
|
||||
<p className="hint">Indica por dónde empieza el día: si no es «Plan del Día» o «Calendario», la entrada principal no está cumpliendo su función.</p>
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Página</th><th className="num">Veces que fue la primera del día</th></tr></thead>
|
||||
<tbody>
|
||||
{u.primeraDelDia.map((r) => <tr key={r.ruta}><td>{nom(r.ruta)}</td><td className="num">{r.n}</td></tr>)}
|
||||
{!u.primeraDelDia.length && <tr><td colSpan={2}>Sin datos todavía.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</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}` : "/");
|
||||
}
|
||||
195
app/agendador/agendadorActions.js
Normal file
195
app/agendador/agendadorActions.js
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
"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 } from "../lib/plan";
|
||||
import { TIPOS_AGENDADOR, OBJETIVOS_AGENDADOR, validar, resumenExistentes, localDeIso, ventanaDe, fechaMaxima } from "../lib/agendador";
|
||||
import {
|
||||
objetivosPorNombre, actividadesFrescas, oportunidadesFrescas, crearActividad, cancelarActividad,
|
||||
} from "../lib/agendadorServer";
|
||||
import { guardarLote, getLote, marcarDeshecho } from "../lib/agendadorLotes";
|
||||
import { GC } from "../lib/participantes";
|
||||
import { sumarParticipacionOpp, restaurarParticipacionOpp } from "../lib/actividadesServer";
|
||||
|
||||
// Igual que en gestionActions: con PARTICIPANTES_OPP=off no se toca la participación de la oportunidad.
|
||||
const oppApagado = () => String(process.env.PARTICIPANTES_OPP || "").toLowerCase() === "off";
|
||||
|
||||
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("/agendador");
|
||||
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, fecha, 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();
|
||||
// Días de agendado: 5 días hábiles desde la fecha elegida (hoy como mínimo, hoy + 30 días como máximo).
|
||||
const fechaTxt = String(fecha || "");
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(fechaTxt) || fechaTxt > fechaMaxima(hoy)) {
|
||||
return { ok: false, error: "La fecha de agendado debe estar entre hoy y los próximos 30 días." };
|
||||
}
|
||||
const dias = ventanaDe(fechaTxt, hoy);
|
||||
if (!dias.length) return { ok: false, error: "No hay días hábiles para agendar con esa fecha." };
|
||||
const rango = { desde: dias[0], hasta: dias[dias.length - 1] };
|
||||
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 || ""),
|
||||
gv: i?.gv === true && (i?.tipo === "Llamada" || i?.tipo === "Cita"), // «Con GV»: solo llamadas y visitas
|
||||
}));
|
||||
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 en esos días." }); 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);
|
||||
const hecho = { oppId: it.oppId, nombre: it.nombre, cliente: it.cliente, tipo: it.tipo, objetivo: it.objetivo, dia: it.dia, hora: it.hora, gv: it.gv, estado: "creada", activityId: id };
|
||||
// «Con GV»: se marca «Participación de GV» en la oportunidad AL AGENDAR (decisión de Marco). Solo suma (nunca baja
|
||||
// un Sí a No) y se guarda lo previo para «Deshacer». Si falla, la actividad queda creada y solo se avisa.
|
||||
if (it.gv && !oppApagado()) {
|
||||
try {
|
||||
const r = await sumarParticipacionOpp(token, it.oppId, [GC]);
|
||||
if (r.cambio) hecho.opp = { previo: r.previo, nuevo: r.nuevo };
|
||||
} catch (e) {
|
||||
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||||
hecho.avisoOpp = "No pude marcar la participación de GV en la oportunidad; márcala en Dynamics.";
|
||||
}
|
||||
}
|
||||
hechos.push(hecho);
|
||||
} 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, gv: it.gv, 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,
|
||||
conGV: hechos.filter((h) => h.estado === "creada" && h.gv).length,
|
||||
avisosOpp: hechos.filter((h) => h.avisoOpp).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, oppRestauradas: 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++;
|
||||
// La oportunidad vuelve a su valor previo SOLO si esta tanda la cambió y la actividad se canceló aquí
|
||||
// (si ya se completó, la participación de GV pudo ser real y se deja).
|
||||
if (it.opp?.previo && it.opp?.nuevo && !oppApagado()) {
|
||||
try {
|
||||
await restaurarParticipacionOpp(session.accessToken, it.opp.previo, it.opp.nuevo);
|
||||
resumen.oppRestauradas++;
|
||||
} catch (e) {
|
||||
if (e?.message === "TOKEN_EXPIRED") throw e;
|
||||
resumen.errores++;
|
||||
}
|
||||
}
|
||||
} 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/agendador/loading.js
Normal file
4
app/agendador/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import PageLoading from "../components/PageLoading";
|
||||
export default function Loading() {
|
||||
return <PageLoading />;
|
||||
}
|
||||
127
app/agendador/page.js
Normal file
127
app/agendador/page.js
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
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, fechaMaxima } from "../lib/agendador";
|
||||
import { getLotesRecientes } from "../lib/agendadorLotes";
|
||||
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import { hoyManagua, diaDe, objetivoSugerido, COD_RENOVACION } from "../lib/plan";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import OwnerControl from "../components/OwnerControl";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import AgendadorPanel from "../components/plan/AgendadorPanel";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Agendador de actividades — página INDEPENDIENTE del Plan de Actividades (2026-11-06). Para UN ejecutivo
|
||||
// del piloto, trae TODAS sus oportunidades abiertas (sin esconder ninguna por su fecha de cierre) y deja
|
||||
// agendar desde hoy hasta hoy + 30 días. Diseño: agendador-automatico-diseno.md.
|
||||
export default async function Agendador({ 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 ownerAgenda = scope.emails.length === 1 ? scope.emails[0] : null;
|
||||
const puedeAgendar = !!ownerAgenda && puedeAgendarPara(session, ownerAgenda);
|
||||
|
||||
let allUsers = [];
|
||||
try {
|
||||
allUsers = session.isAdmin || scope.asistente ? await getSystemUsers(session.accessToken) : [];
|
||||
} 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 cabecera = (
|
||||
<div className="no-print agd-cab">
|
||||
<h1 className="agd-h1">Agendador de actividades</h1>
|
||||
<div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
|
||||
{puedeAgendar && <Link href={`/actividades?owner=${ownerAgenda}`} className="agd-enlace">Ver el Plan de Actividades →</Link>}
|
||||
<Suspense fallback={null}>
|
||||
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!puedeAgendar) {
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
{cabecera}
|
||||
<section className="panel plan-agd no-print">
|
||||
<div className="agd-ayuda">
|
||||
<p>
|
||||
{ownerAgenda
|
||||
? "El agendador de actividades no está habilitado para este usuario."
|
||||
: "Elige arriba, en «Propietario», un solo ejecutivo para ver su agendador."}
|
||||
{" "}Está habilitado para: <b>{AGENDADOR.piloto.join(", ")}</b>.
|
||||
</p>
|
||||
<p><Link href="/actividades">← Ir al Plan de Actividades</Link></p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
let raw, opps, ownerId;
|
||||
try {
|
||||
[raw, opps, ownerId] = await Promise.all([
|
||||
getActividades(session.accessToken, scope),
|
||||
// TODAS las abiertas del ejecutivo: el filtro «Cierre estimado» y el buscador las acotan en pantalla.
|
||||
getOportunidadesSemana(session.accessToken, scope, null, null),
|
||||
resolveOwnerId(ownerAgenda, session.accessToken),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
let lotes = [];
|
||||
try {
|
||||
lotes = ownerId ? getLotesRecientes(ownerId) : [];
|
||||
} catch { /* sin historial de tandas: el agendador funciona igual */ }
|
||||
|
||||
// Actividades no canceladas por oportunidad, con su fecha (para saber cuáles ya tienen algo agendado
|
||||
// en los días que se están planificando). Solo importan las de hoy en adelante.
|
||||
const maxFecha = fechaMaxima(hoy);
|
||||
const actPorOpp = {};
|
||||
for (const a of raw) {
|
||||
const oppId = a.oportunidad?.id;
|
||||
if (a.estado === "cancelada" || !oppId) continue;
|
||||
const d = diaDe(a);
|
||||
if (!d || d < hoy || d > maxFecha) continue;
|
||||
(actPorOpp[oppId] ||= []).push(d);
|
||||
}
|
||||
const { existentes, bloques } = resumenExistentes(raw);
|
||||
|
||||
// `?fecha=YYYY-MM-DD` (desde «Agendar ▸» del Plan del Día): abre el agendador con esa fecha, solo si cae entre hoy y el horizonte.
|
||||
const fechaInicial = /^\d{4}-\d{2}-\d{2}$/.test(sp.fecha || "") && sp.fecha >= hoy && sp.fecha <= maxFecha ? sp.fecha : null;
|
||||
|
||||
const props = {
|
||||
fechaInicial,
|
||||
ownerEmail: ownerAgenda,
|
||||
ownerName: allUsers.find((u) => u.email === ownerAgenda)?.name || opps[0]?.owner || ownerAgenda,
|
||||
hoy,
|
||||
ahoraMin: localDeIso(new Date().toISOString()).min,
|
||||
candidatos: opps.map((o) => ({
|
||||
id: o.id, nombre: o.nombre, cliente: o.cliente, valor: o.valor, pct: parseInt(o.forecast || "", 10) || 0,
|
||||
tipoCodigo: o.tipoCodigo, esRenovacion: COD_RENOVACION.has(o.tipoCodigo), objetivoSugerido: objetivoSugerido(o),
|
||||
tipo: o.tipo || null, plan: o.plan || null, forecast: o.forecast || null, cierre: o.cierre || null,
|
||||
})),
|
||||
actPorOpp,
|
||||
existentes,
|
||||
bloques,
|
||||
lotes,
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
{cabecera}
|
||||
<AgendadorPanel key={`${ownerAgenda}|${fechaInicial || ""}`} {...props} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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;
|
||||
30
app/api/campanita/route.js
Normal file
30
app/api/campanita/route.js
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { NextResponse } from "next/server";
|
||||
import { auth } from "../../lib/auth";
|
||||
import { ownerFilter } from "../../lib/authz";
|
||||
import { getActividades } from "../../lib/queries";
|
||||
import { hoyManagua } from "../../lib/plan";
|
||||
import { localDeIso } from "../../lib/agendador";
|
||||
import { armarCampanita } from "../../lib/campanita";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Datos de la campanita con la sesión de quien consulta. Ejecutivo (y asistente): sus propias actividades.
|
||||
// Administrador sin `owner`: solo las actividades con Gerencia Comercial de cualquier ejecutivo.
|
||||
// `owner` (solo administrador, para validar): ve lo que vería ese ejecutivo. `fresh=1`: sin caché (tras gestionar).
|
||||
export async function GET(req) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return NextResponse.json({ ok: false, error: "sin_sesion" }, { status: 401 });
|
||||
const url = new URL(req.url);
|
||||
const owner = session.isAdmin ? url.searchParams.get("owner") || undefined : undefined;
|
||||
const scope = ownerFilter(session, owner);
|
||||
try {
|
||||
const acts = await getActividades(session.accessToken, scope, undefined, { fresh: url.searchParams.get("fresh") === "1" });
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||||
const data = armarCampanita(acts, { hoy: hoyManagua(), ahoraMin, gerente: !!session.isAdmin && !owner });
|
||||
const acciones = String(process.env.ACTIVIDADES_ACCIONES || "").toLowerCase() !== "off"; // con «off» no se ofrece «Gestionar»
|
||||
return NextResponse.json({ ok: true, ...data, ahoraMin, acciones }, { headers: { "Cache-Control": "no-store" } });
|
||||
} catch (e) {
|
||||
const expirada = String(e?.message) === "TOKEN_EXPIRED";
|
||||
return NextResponse.json({ ok: false, error: expirada ? "sesion_expirada" : "error" }, { status: expirada ? 401 : 500 });
|
||||
}
|
||||
}
|
||||
230
app/components/AppShell.js
Normal file
230
app/components/AppShell.js
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
"use client";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import SeccionTabs from "./SeccionTabs";
|
||||
import { registrarVistaAction } from "../uso/usoActions";
|
||||
import { DYN } from "../lib/constants";
|
||||
import Campanita from "./Campanita";
|
||||
import CampoShell from "../m/components/CampoShell";
|
||||
|
||||
// Altas que se hacen en Dynamics (la app no las cubre): se abren directo en el formulario nuevo.
|
||||
const nuevoEnDynamics = (etn) => DYN.replace("etn=opportunity", `etn=${etn}`).replace(/&id=$/, "");
|
||||
const CREAR_EN_DYNAMICS = [
|
||||
["Nueva oportunidad", "opportunity"],
|
||||
["Nueva cuenta", "account"],
|
||||
["Nuevo cliente potencial", "lead"],
|
||||
["Nueva oferta", "quote"],
|
||||
];
|
||||
|
||||
// Grupo del menú; si `plegado`, se muestra recogido (se abre solo cuando la página actual es de ese grupo).
|
||||
function Grupo({ g, plegado, activoAqui, children }) {
|
||||
return plegado ? (
|
||||
<details open={activoAqui} className="nav-plegable">
|
||||
<summary className="nav-grupo" style={{ cursor: "pointer" }}>{g}</summary>
|
||||
{children}
|
||||
</details>
|
||||
) : (
|
||||
<div>
|
||||
<div className="nav-grupo">{g}</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 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();
|
||||
// «Ver el menú como»: el gerente puede ver el menú tal como lo ve un ejecutivo (solo cambia el menú, no los datos).
|
||||
const [comoEjecutivo, setComoEjecutivo] = useState(false);
|
||||
useEffect(() => {
|
||||
try { setComoEjecutivo(localStorage.getItem("informe.menuComo") === "ejecutivo"); } catch { /* sin almacenamiento */ }
|
||||
}, []);
|
||||
const cambiarMenu = (v) => {
|
||||
setComoEjecutivo(v);
|
||||
try { localStorage.setItem("informe.menuComo", v ? "ejecutivo" : "gerente"); } catch { /* ignorar */ }
|
||||
};
|
||||
const verComoGerente = !!session?.isAdmin && !comoEjecutivo;
|
||||
const email = session?.email || null;
|
||||
// `soloGerente`: entradas que solo ve el gerente (y solo con el menú en modo gerente).
|
||||
const visibles = pages.filter((p) => !p.soloGerente || verComoGerente);
|
||||
const grupos = [...new Set(visibles.map((p) => p.grupo))];
|
||||
|
||||
// Registro de uso: una visita por cambio de página (solo con sesión). Nunca bloquea ni muestra errores.
|
||||
useEffect(() => {
|
||||
if (!email) return;
|
||||
try {
|
||||
const owner = new URLSearchParams(window.location.search).get("owner");
|
||||
registrarVistaAction({ ruta: pathname, owner, ancho: window.innerWidth });
|
||||
} catch { /* ignorar */ }
|
||||
}, [pathname, email]);
|
||||
|
||||
// Aviso discreto en teléfono (ancho ≤ 600 px): ofrecer la versión de campo. Descartable y recordado.
|
||||
const [avisoCampo, setAvisoCampo] = useState(false);
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (window.innerWidth <= 600 && email && !localStorage.getItem("informe.avisoCampo")) setAvisoCampo(true);
|
||||
} catch { /* sin almacenamiento */ }
|
||||
}, [email]);
|
||||
const descartarAviso = () => {
|
||||
setAvisoCampo(false);
|
||||
try { localStorage.setItem("informe.avisoCampo", "1"); } catch { /* ignorar */ }
|
||||
};
|
||||
|
||||
// La app de campo (/m) tiene su propio marco: sin menú lateral.
|
||||
if (pathname === "/m" || pathname?.startsWith("/m/")) {
|
||||
return <CampoShell session={session} onSignIn={onSignIn} onSignOut={onSignOut}>{children}</CampoShell>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{avisoCampo && (
|
||||
<div className="aviso-campo" role="note">
|
||||
<Link href="/m/hoy" onClick={descartarAviso}>Usar la versión de campo →</Link>
|
||||
<button type="button" aria-label="Descartar aviso" onClick={descartarAviso}>✕</button>
|
||||
</div>
|
||||
)}
|
||||
<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) => {
|
||||
const items = visibles.filter((p) => p.grupo === g);
|
||||
const plegado = items.every((p) => p.colapsado) && !verComoGerente;
|
||||
const activoAqui = items.some((p) => pathname === p.href || p.alias?.includes(pathname));
|
||||
return (
|
||||
<Grupo key={g} g={g} plegado={plegado} activoAqui={activoAqui}>
|
||||
{items
|
||||
.map((p) =>
|
||||
p.built ? (
|
||||
<OwnerAwareLink
|
||||
key={p.href}
|
||||
href={p.href}
|
||||
className={`nav-item${pathname === p.href || p.alias?.includes(pathname) ? " 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>
|
||||
)
|
||||
)}
|
||||
</Grupo>
|
||||
);
|
||||
})}
|
||||
<div>
|
||||
<div className="nav-grupo">Crear en Dynamics ↗</div>
|
||||
{CREAR_EN_DYNAMICS.map(([label, etn]) => (
|
||||
<a key={etn} className="nav-item" href={nuevoEnDynamics(etn)} target="_blank" rel="noopener" style={{ textDecoration: "none" }}>
|
||||
<span className="ico">+</span>
|
||||
{label}
|
||||
</a>
|
||||
))}
|
||||
</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>
|
||||
{session?.email && <Campanita />}
|
||||
<div className="ctrl" style={session?.email ? undefined : { marginLeft: "auto" }}>
|
||||
{session?.email ? (
|
||||
<>
|
||||
{session.isAdmin && (
|
||||
<>
|
||||
<span className="seg-tabs" style={{ marginRight: 12 }} title="Ver el menú como lo ve un ejecutivo (no cambia los datos)">
|
||||
<button type="button" className={!comoEjecutivo ? "on" : ""} onClick={() => cambiarMenu(false)}>Menú gerente</button>
|
||||
<button type="button" className={comoEjecutivo ? "on" : ""} onClick={() => cambiarMenu(true)}>Ver como ejecutivo</button>
|
||||
</span>
|
||||
<Link href="/admin/uso" style={{ marginRight: 12, fontSize: 13, color: "var(--marca)" }}>
|
||||
📊 Uso
|
||||
</Link>
|
||||
<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">
|
||||
<SeccionTabs />
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
59
app/components/BuscadorOportunidades.js
Normal file
59
app/components/BuscadorOportunidades.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
"use client";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
// Buscador de oportunidades para las páginas de previsión y tubería (ventas y renovaciones). Filtra las
|
||||
// FILAS de todas las tablas de la página por nombre de oportunidad o de cliente (sin tildes ni mayúsculas).
|
||||
// No recalcula las tarjetas ni los totales: es una ayuda para ubicar una oportunidad, no un filtro de datos.
|
||||
const norm = (s) => String(s || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||
|
||||
export default function BuscadorOportunidades() {
|
||||
const [q, setQ] = useState("");
|
||||
const [vis, setVis] = useState(null); // { mostradas, total } mientras hay búsqueda
|
||||
const qRef = useRef("");
|
||||
qRef.current = q;
|
||||
|
||||
useEffect(() => {
|
||||
let temporizador = null;
|
||||
const aplicar = () => {
|
||||
const t = norm(qRef.current).trim();
|
||||
const filas = [...document.querySelectorAll("main table tbody tr, .tw table tbody tr")].filter((tr) => tr.querySelector("a.opp"));
|
||||
let ok = 0;
|
||||
for (const tr of new Set(filas)) {
|
||||
const coincide = !t || norm(tr.textContent).includes(t);
|
||||
tr.hidden = !coincide;
|
||||
if (coincide) ok++;
|
||||
}
|
||||
setVis(t ? { mostradas: ok, total: new Set(filas).size } : null);
|
||||
};
|
||||
aplicar();
|
||||
// Si la página se vuelve a pintar (cambia un filtro), se vuelve a aplicar la búsqueda.
|
||||
const obs = new MutationObserver(() => {
|
||||
clearTimeout(temporizador);
|
||||
temporizador = setTimeout(aplicar, 120);
|
||||
});
|
||||
obs.observe(document.body, { childList: true, subtree: true });
|
||||
return () => {
|
||||
obs.disconnect();
|
||||
clearTimeout(temporizador);
|
||||
document.querySelectorAll("tr[hidden]").forEach((tr) => { tr.hidden = false; });
|
||||
};
|
||||
}, [q]);
|
||||
|
||||
return (
|
||||
<div className="busca-opp">
|
||||
<input
|
||||
type="search"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="🔍 Buscar oportunidad o cliente…"
|
||||
aria-label="Buscar oportunidad o cliente"
|
||||
/>
|
||||
{vis && (
|
||||
<span className="busca-n">
|
||||
{vis.mostradas === 0 ? "Sin coincidencias en las tablas" : `${vis.mostradas} de ${vis.total} filas`}
|
||||
{" · "}<button type="button" onClick={() => setQ("")}>Limpiar</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
153
app/components/Campanita.js
Normal file
153
app/components/Campanita.js
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
"use client";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import GestionarActividad from "./actividades/GestionarActividad";
|
||||
import { ICONO_TIPO, ROTULO_TIPO } from "../lib/agendaDia";
|
||||
|
||||
// Campanita de notificaciones (etapa 1, solo web). Muestra lo que pide acción hoy: actividades vencidas sin completar
|
||||
// y las que vienen. Datos de /api/campanita (sesión del usuario). Se actualiza al cargar, al abrir el panel (si los datos
|
||||
// tienen más de 1 min) y cada 5 min mientras la pestaña está visible; tras gestionar una actividad vuelve a leer sin caché.
|
||||
const CADA_MS = 5 * 60 * 1000;
|
||||
const FRESCO_MS = 60 * 1000;
|
||||
const MAX_PROXIMAS = 6;
|
||||
|
||||
export default function Campanita({ rutaPlan = "/plan", rutaVenc = "/actividades?periodo=mes&venc=1" }) {
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const [d, setD] = useState(null);
|
||||
const [error, setError] = useState(false);
|
||||
const raiz = useRef(null);
|
||||
const ultima = useRef(0);
|
||||
const gestionando = useRef(0); // ventanas «Gestionar» abiertas: mientras haya una, no se reemplaza la lista
|
||||
const cargando = useRef(false);
|
||||
|
||||
const cargar = useCallback(async (fresh = false) => {
|
||||
if (cargando.current) return;
|
||||
cargando.current = true;
|
||||
try {
|
||||
const r = await fetch(`/api/campanita${fresh ? "?fresh=1" : ""}`, { cache: "no-store" });
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
const j = await r.json();
|
||||
if (!j.ok) throw new Error(j.error || "error");
|
||||
if (gestionando.current === 0) setD(j);
|
||||
ultima.current = Date.now();
|
||||
setError(false);
|
||||
} catch {
|
||||
setError(true);
|
||||
} finally {
|
||||
cargando.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
cargar();
|
||||
const t = setInterval(() => {
|
||||
if (document.visibilityState === "visible" && gestionando.current === 0) cargar();
|
||||
}, CADA_MS);
|
||||
const vis = () => {
|
||||
if (document.visibilityState === "visible" && Date.now() - ultima.current > CADA_MS) cargar();
|
||||
};
|
||||
document.addEventListener("visibilitychange", vis);
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
document.removeEventListener("visibilitychange", vis);
|
||||
};
|
||||
}, [cargar]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!abierto) return;
|
||||
const clic = (e) => {
|
||||
if (raiz.current?.contains(e.target) || e.target.closest?.(".gst-bd")) return; // la ventana «Gestionar» vive fuera del panel
|
||||
setAbierto(false);
|
||||
};
|
||||
const tecla = (e) => {
|
||||
if (e.key === "Escape" && gestionando.current === 0) setAbierto(false);
|
||||
};
|
||||
document.addEventListener("mousedown", clic);
|
||||
document.addEventListener("keydown", tecla);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", clic);
|
||||
document.removeEventListener("keydown", tecla);
|
||||
};
|
||||
}, [abierto]);
|
||||
|
||||
const alternar = () => {
|
||||
const nuevo = !abierto;
|
||||
setAbierto(nuevo);
|
||||
if (nuevo && Date.now() - ultima.current > FRESCO_MS) cargar();
|
||||
};
|
||||
const alAbrir = () => {
|
||||
gestionando.current++;
|
||||
};
|
||||
const alCerrar = (cambio) => {
|
||||
gestionando.current = Math.max(0, gestionando.current - 1);
|
||||
cargar(cambio);
|
||||
};
|
||||
|
||||
const n = d?.numero || 0;
|
||||
const visibles = d ? d.proximas.slice(0, MAX_PROXIMAS) : [];
|
||||
const resto = d ? d.proximas.length - visibles.length : 0;
|
||||
|
||||
const fila = (it, hecho) => (
|
||||
<li key={it.id} className={`bell-it${hecho ? " bell-hecho" : ""}${it.enMin != null ? " bell-ya" : ""}`}>
|
||||
<span className="bell-h">{hecho ? "✓ " : ""}{it.hora || "—"}</span>
|
||||
<span className="bell-c">
|
||||
<b>{ICONO_TIPO[it.tipo]} {it.cliente}{it.esCaso && <span className="bell-ref"> (caso)</span>}{it.esCuenta && <span className="bell-ref"> (cuenta)</span>}</b>
|
||||
<small>
|
||||
{ROTULO_TIPO[it.tipo] || it.tipo} · {it.objetivo}
|
||||
{it.enMin != null && <em> · {it.enMin <= 0 ? "ahora" : `en ${it.enMin} min`}</em>}
|
||||
</small>
|
||||
</span>
|
||||
{!hecho && d.acciones && (
|
||||
<GestionarActividad a={it.a} className="bell-gst" title={`Gestionar: ${it.a.asunto || it.tipo}`} onAbrir={alAbrir} onCerrado={alCerrar}>Gestionar</GestionarActividad>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="bell" ref={raiz}>
|
||||
<button
|
||||
type="button"
|
||||
className="bell-btn"
|
||||
aria-label={n ? `Notificaciones: ${n} pendiente${n === 1 ? "" : "s"}` : "Notificaciones"}
|
||||
aria-expanded={abierto}
|
||||
aria-haspopup="true"
|
||||
onClick={alternar}
|
||||
>
|
||||
<span aria-hidden="true">🔔</span>
|
||||
{n > 0 && <span className="bell-n" aria-hidden="true">{n > 99 ? "99+" : n}</span>}
|
||||
</button>
|
||||
{/* El panel se queda montado (oculto) para no desmontar una ventana «Gestionar» abierta desde él. */}
|
||||
<div className="bell-panel" hidden={!abierto} role="region" aria-label="Notificaciones">
|
||||
<div className="bell-top">
|
||||
<b>Notificaciones</b>
|
||||
<Link href={rutaPlan} onClick={() => setAbierto(false)}>Ver Plan del Día →</Link>
|
||||
</div>
|
||||
{!d && !error && <p className="bell-vacio">Cargando…</p>}
|
||||
{error && !d && <p className="bell-vacio">No se pudieron leer las notificaciones. Se reintenta solo.</p>}
|
||||
{d && (
|
||||
<>
|
||||
{d.vencidas > 0 && (
|
||||
<div className="bell-venc">
|
||||
<span>⚠ {d.vencidas} {d.vencidas === 1 ? "actividad vencida" : "actividades vencidas"} sin completar</span>
|
||||
<Link href={rutaVenc} onClick={() => setAbierto(false)}>Revisar</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="bell-grp">Próximas · hoy{d.gerente ? " · con Gerencia Comercial" : ""}</div>
|
||||
{visibles.length ? (
|
||||
<ul className="bell-lista">{visibles.map((it) => fila(it, false))}</ul>
|
||||
) : (
|
||||
<p className="bell-vacio">{d.gerente ? "No hay actividades con Gerencia Comercial pendientes hoy." : "No te quedan actividades pendientes hoy."}</p>
|
||||
)}
|
||||
{resto > 0 && <Link className="bell-mas" href={rutaPlan} onClick={() => setAbierto(false)}>+{resto} más · ver todas en el Plan →</Link>}
|
||||
{d.hechas.length > 0 && (
|
||||
<>
|
||||
<div className="bell-grp">Hecho hoy</div>
|
||||
<ul className="bell-lista">{d.hechas.map((it) => fila(it, true))}</ul>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</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>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
42
app/components/SeccionTabs.js
Normal file
42
app/components/SeccionTabs.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"use client";
|
||||
import { Suspense } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { seccionDe } from "../lib/secciones";
|
||||
|
||||
// Barra de pestañas de una sección (Cierres, Resultados, Semana). Va arriba de las páginas que pertenecen a una
|
||||
// sección; conserva el filtro de Propietario al cambiar de pestaña o de universo.
|
||||
function Barra() {
|
||||
const pathname = usePathname();
|
||||
const owner = useSearchParams().get("owner");
|
||||
const hit = seccionDe(pathname);
|
||||
if (!hit) return null;
|
||||
const { seccion, vista, universo } = hit;
|
||||
const con = (href) => (owner && href ? `${href}?owner=${encodeURIComponent(owner)}` : href);
|
||||
return (
|
||||
<div className="seccion-tabs no-print">
|
||||
<div className="seg-tabs">
|
||||
{seccion.vistas.map((v) => {
|
||||
const href = universo === "renov" && v.renov ? v.renov : v.ventas;
|
||||
return (
|
||||
<Link key={v.k} href={con(href)} className={v.k === vista.k ? "on" : ""} style={{ textDecoration: "none" }}>{v.label}</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{seccion.interruptor && (
|
||||
<div className="seg-tabs seccion-universo" title="Ventas y Renovaciones son universos distintos: no se suman">
|
||||
<Link href={con(vista.ventas)} className={universo === "ventas" ? "on" : ""} style={{ textDecoration: "none" }}>Ventas</Link>
|
||||
<Link href={con(vista.renov)} className={universo === "renov" ? "on" : ""} style={{ textDecoration: "none" }}>Renovaciones</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SeccionTabs() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Barra />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
45
app/components/actividades/AgendarBoton.js
Normal file
45
app/components/actividades/AgendarBoton.js
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"use client";
|
||||
import { useState } from "react";
|
||||
import NuevaActividad from "./NuevaActividad";
|
||||
import { hoyManagua, addDays, objetivoSugerido } from "../../lib/plan";
|
||||
import { localDeIso, OBJETIVOS_LIBRES } from "../../lib/agendador";
|
||||
|
||||
// Botón «+ Actividad» de las tablas de oportunidades. Reemplaza a los tres enlaces (Cita / Tarea / Llamada) que
|
||||
// abrían el formulario de Dynamics: ahora se abre la ventana de la app, ya ligada a la oportunidad, con el
|
||||
// objetivo sugerido según su etapa. La actividad queda a nombre del propietario de la oportunidad.
|
||||
// `opp`: { id, nombre | name, cliente, ownerId, forecast, tipoCodigo }
|
||||
export default function AgendarBoton({ opp }) {
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const [preset, setPreset] = useState(null);
|
||||
|
||||
function abrir() {
|
||||
const hoy = hoyManagua();
|
||||
const ahora = localDeIso(new Date().toISOString()).min;
|
||||
// Próxima hora en punto dentro del horario (8:00–17:00); si ya pasó, mañana a las 9:00.
|
||||
const sig = Math.ceil((ahora + 1) / 60) * 60;
|
||||
const hoyOk = sig >= 480 && sig <= 1020;
|
||||
const dia = hoyOk ? hoy : addDays(hoy, sig < 480 ? 0 : 1);
|
||||
const min = hoyOk ? sig : 540;
|
||||
const sug = objetivoSugerido(opp);
|
||||
const nombre = opp.nombre || opp.name || "";
|
||||
setPreset({
|
||||
referente: { tipo: "opportunity", id: opp.id, nombre: opp.cliente ? `${opp.cliente} — ${nombre}` : nombre },
|
||||
dia,
|
||||
hora: `${String(Math.floor(min / 60)).padStart(2, "0")}:${String(min % 60).padStart(2, "0")}`,
|
||||
objetivo: sug && OBJETIVOS_LIBRES.includes(sug) ? sug : "",
|
||||
enNombreDe: true, // queda a nombre del propietario de la oportunidad (el servidor valida el permiso)
|
||||
});
|
||||
setAbierto(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="plan-agenda-btns">
|
||||
<button type="button" className="plan-agendar" onClick={abrir} title="Agendar una llamada, visita o tarea para esta oportunidad, sin salir de la app">
|
||||
+ Actividad
|
||||
</button>
|
||||
</span>
|
||||
{abierto && preset && <NuevaActividad hoy={hoyManagua()} preset={preset} onClose={() => setAbierto(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
525
app/components/actividades/GestionarActividad.js
Normal file
525
app/components/actividades/GestionarActividad.js
Normal file
|
|
@ -0,0 +1,525 @@
|
|||
"use client";
|
||||
import { useState, useRef } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { abrirActividadAction, ejecutarAccionAction, deshacerAccionAction, refrescarPantallasAction, crearSeguimientoAction, deshacerSeguimientoAction, editarActividadAction, deshacerEdicionAction } from "../../actividades/gestionActions";
|
||||
import { actividadUrl } from "../../lib/constants";
|
||||
import { addDays, esHabil } from "../../lib/plan";
|
||||
import { ROLES, nombresDe } from "../../lib/participantes";
|
||||
import { AGENDADOR, OBJETIVOS_LIBRES, horasDe, horasLibres, horaAMin, localDeIso, minAHora } from "../../lib/agendador";
|
||||
import { clienteDe, oportunidadDe } from "../../lib/agendaVista";
|
||||
|
||||
// Ventana emergente para completar, reprogramar o cancelar UNA actividad sin salir del informe. Pensada
|
||||
// para pocos toques: fechas y horas por botones (no menús), nota breve con frases rápidas y «Deshacer».
|
||||
// El mismo componente sirve luego a la versión móvil: no depende de la pantalla donde se abre.
|
||||
|
||||
export const FRASES = {
|
||||
Llamada: ["No contestó", "Dejé mensaje", "Habló con el decisor", "Interesado", "Pidió propuesta", "Llamar de nuevo"],
|
||||
Cita: ["Visita realizada", "Se presentó la oferta", "Pidió ajustes", "Pasan a revisión interna", "Se definió fecha de firma"],
|
||||
Tarea: ["Oferta enviada", "Contrato elaborado", "Seguimiento realizado", "Pendiente de respuesta del cliente"],
|
||||
};
|
||||
const HORAS = ["08:00", "09:00", "10:00", "11:00", "14:00", "15:00", "16:00"];
|
||||
const DIAS = ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
|
||||
const MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||||
|
||||
const dow = (iso) => new Date(`${iso}T12:00:00Z`).getUTCDay();
|
||||
const etiqueta = (iso) => {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
return `${DIAS[dow(iso)]} ${d} ${MESES[m - 1]}`;
|
||||
};
|
||||
function proximoLunes(hoy) {
|
||||
let d = addDays(hoy, 1);
|
||||
while (dow(d) !== 1) d = addDays(d, 1);
|
||||
return d;
|
||||
}
|
||||
const horaLocal = (iso) => {
|
||||
if (!iso) return "";
|
||||
const d = new Date(new Date(iso).getTime() - 6 * 3600 * 1000);
|
||||
return `${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
export default function GestionarActividad({ a, className, title, children, onAbrir, onCerrado }) {
|
||||
const router = useRouter();
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
const [carga, setCarga] = useState("idle"); // idle | cargando | listo | error
|
||||
const [det, setDet] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
const [accion, setAccion] = useState("completar");
|
||||
const [nota, setNota] = useState("");
|
||||
const [dia, setDia] = useState("");
|
||||
const [hora, setHora] = useState("");
|
||||
const [confirma, setConfirma] = useState(false);
|
||||
const [trabajando, setTrabajando] = useState(false);
|
||||
const [roles, setRoles] = useState([]); // códigos de quienes participaron (solo al completar)
|
||||
const [hecho, setHecho] = useState(null); // { accionId, accion, ... }
|
||||
const [deshecho, setDeshecho] = useState(false);
|
||||
const huboCambio = useRef(false);
|
||||
// Pestaña «Editar»: cambios sin completar la actividad (objetivo, duración, nota previa, participantes de la visita).
|
||||
const [objEd, setObjEd] = useState("");
|
||||
const [durEd, setDurEd] = useState(null);
|
||||
const [notaEd, setNotaEd] = useState("");
|
||||
const [rolesEd, setRolesEd] = useState([]);
|
||||
// Seguimiento: programar la siguiente actividad justo después de completar.
|
||||
const [segAbierto, setSegAbierto] = useState(false);
|
||||
const [segTipo, setSegTipo] = useState("Llamada");
|
||||
const [segObj, setSegObj] = useState("");
|
||||
const [segDia, setSegDia] = useState("");
|
||||
const [segHora, setSegHora] = useState("09:00");
|
||||
const [segTrab, setSegTrab] = useState(false);
|
||||
const [segError, setSegError] = useState("");
|
||||
const [seg, setSeg] = useState(null); // { accionId, tipo, dia, hora } cuando se creó
|
||||
const [segDeshecho, setSegDeshecho] = useState(false);
|
||||
|
||||
async function abrir() {
|
||||
setAbierto(true);
|
||||
if (onAbrir) onAbrir();
|
||||
setCarga("cargando");
|
||||
setError("");
|
||||
setHecho(null);
|
||||
setDeshecho(false);
|
||||
setConfirma(false);
|
||||
setNota("");
|
||||
setAccion("completar");
|
||||
setSegAbierto(false);
|
||||
setSeg(null);
|
||||
setSegDeshecho(false);
|
||||
setSegError("");
|
||||
const r = await abrirActividadAction({ tipo: a.tipo, id: a.id });
|
||||
if (!r.ok) {
|
||||
setError(r.error);
|
||||
setCarga("error");
|
||||
return;
|
||||
}
|
||||
setDet(r.actividad);
|
||||
setRoles(r.actividad.participantes || []); // en una cita ya marcada, parte de lo que tenía
|
||||
setRolesEd(r.actividad.participantes || []);
|
||||
setObjEd(OBJETIVOS_LIBRES.includes(r.actividad.objetivo) ? r.actividad.objetivo : "");
|
||||
setDurEd(r.actividad.duracion || null);
|
||||
setNotaEd("");
|
||||
setDia(r.actividad.hoy);
|
||||
setSegTipo(a.tipo === "Cita" ? "Llamada" : a.tipo);
|
||||
setSegObj(OBJETIVOS_LIBRES.includes(r.actividad.objetivo) ? r.actividad.objetivo : "");
|
||||
let sig = addDays(r.actividad.hoy, 1);
|
||||
while (!esHabil(sig)) sig = addDays(sig, 1);
|
||||
setSegDia(sig);
|
||||
setHora(horaLocal(r.actividad.scheduledstart) || "09:00");
|
||||
setCarga(r.apagado ? "apagado" : "listo");
|
||||
}
|
||||
|
||||
async function cerrar() {
|
||||
// «Listo»/✕/clic fuera con un seguimiento a medio llenar (abierto, sin guardar): se pide confirmación antes de descartarlo.
|
||||
if (hecho && hecho.accion === "completar" && !deshecho && det?.tieneOpp && segAbierto && !seg && !segDeshecho && !window.confirm("Tienes un seguimiento sin guardar. ¿Cerrar sin guardarlo?")) return;
|
||||
setAbierto(false);
|
||||
const cambio = huboCambio.current;
|
||||
if (cambio) {
|
||||
huboCambio.current = false;
|
||||
await refrescarPantallasAction(); // vacía la caché de datos de las pantallas afectadas
|
||||
router.refresh();
|
||||
}
|
||||
if (onCerrado) onCerrado(cambio); // la campanita se actualiza al cerrar (sin caché si hubo cambios)
|
||||
}
|
||||
|
||||
async function ejecutar() {
|
||||
if (accion === "editar") {
|
||||
setTrabajando(true);
|
||||
setError("");
|
||||
const r = await editarActividadAction({ tipo: a.tipo, id: a.id, objetivo: objEd, duracion: a.tipo === "Tarea" ? null : durEd, nota: notaEd, participantes: a.tipo === "Cita" || a.tipo === "Llamada" ? rolesEd : null });
|
||||
setTrabajando(false);
|
||||
if (!r.ok) {
|
||||
setError(r.error);
|
||||
return;
|
||||
}
|
||||
huboCambio.current = true;
|
||||
setHecho(r);
|
||||
return;
|
||||
}
|
||||
if (accion === "completar" && !nota.trim() && !confirma) {
|
||||
setConfirma(true);
|
||||
return;
|
||||
}
|
||||
if (accion === "cancelar" && !confirma) {
|
||||
setConfirma(true);
|
||||
return;
|
||||
}
|
||||
setTrabajando(true);
|
||||
setError("");
|
||||
const r = await ejecutarAccionAction({ tipo: a.tipo, id: a.id, accion, nota, dia, hora, participantes: accion === "completar" ? roles : [] });
|
||||
if (!r.ok) {
|
||||
setTrabajando(false);
|
||||
setError(r.error);
|
||||
setConfirma(false);
|
||||
return;
|
||||
}
|
||||
huboCambio.current = true;
|
||||
setHecho(r);
|
||||
// Un solo botón: si el formulario de seguimiento estaba abierto y completo, se crea justo después de completar.
|
||||
// Si el seguimiento falla, la actividad ya quedó completada y el formulario sigue abierto para reintentar.
|
||||
if (accion === "completar" && quiereSeg) await guardarSeguimiento();
|
||||
setTrabajando(false);
|
||||
}
|
||||
|
||||
async function deshacer() {
|
||||
setTrabajando(true);
|
||||
setError("");
|
||||
const r = hecho.accion === "editar" ? await deshacerEdicionAction(hecho.accionId) : await deshacerAccionAction(hecho.accionId);
|
||||
setTrabajando(false);
|
||||
if (!r.ok) {
|
||||
setError(r.error);
|
||||
return;
|
||||
}
|
||||
setDeshecho(true);
|
||||
}
|
||||
|
||||
const cerrada = det && det.estado !== "abierta";
|
||||
const conInvitados = det?.tipo === "Cita" && det.invitados > 0;
|
||||
const bloqueaFecha = conInvitados && (accion === "reprogramar" || accion === "cancelar");
|
||||
const hoy = det?.hoy;
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min; // hora de Managua, se recalcula en cada pintado
|
||||
const hoyBloques = det?.hoyAgenda?.bloques || [];
|
||||
const rapidos = hoy
|
||||
? [["Hoy", hoy], ["Mañana", addDays(hoy, 1)], ["Pasado mañana", addDays(hoy, 2)], ["Lunes", proximoLunes(hoy)]]
|
||||
: [];
|
||||
const esTarea = a.tipo === "Tarea";
|
||||
const horaPasada = !esTarea && !!hora && dia === hoy && (horaAMin(hora) ?? 9999) < ahoraMin;
|
||||
const crm = actividadUrl({ tipo: a.tipo, id: a.id });
|
||||
const fraseDe = (f) => setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f));
|
||||
|
||||
// El botón de abajo es el que guarda en Dynamics; las pestañas de arriba solo eligen la acción.
|
||||
// Seguimiento (solo si la actividad está ligada a una oportunidad): válido si tiene objetivo y un día hábil.
|
||||
const segDiaMalo = segAbierto && !!segDia && !esHabil(segDia);
|
||||
// Horas del seguimiento: si el día es hoy, solo futuras y sin choques con lo ya agendado; la elegida se ajusta sola.
|
||||
const horasSeg = hoy ? horasLibres({ tipo: segTipo, dia: segDia, hoy, ahoraMin, bloques: hoyBloques }) : [];
|
||||
const horaSeg = horasSeg.includes(segHora) ? segHora : horasSeg[0] || "";
|
||||
const segSinHoras = segTipo !== "Tarea" && !!segDia && horasSeg.length === 0;
|
||||
const segListo = segAbierto && !!segObj && !!segDia && !segDiaMalo && !segSinHoras;
|
||||
const quiereSeg = segAbierto && !!det?.tieneOpp && segListo;
|
||||
const textoAccion = { completar: segAbierto && det?.tieneOpp ? "Guardar, completar y programar seguimiento" : "Guardar y completar", reprogramar: "Guardar nueva fecha", cancelar: "Cancelar actividad", editar: "Guardar cambios" }[accion];
|
||||
|
||||
async function guardarSeguimiento() {
|
||||
setSegTrab(true);
|
||||
setSegError("");
|
||||
const r = await crearSeguimientoAction({ tipo: a.tipo, id: a.id, nuevoTipo: segTipo, objetivo: segObj, dia: segDia, hora: segTipo === "Tarea" ? "" : horaSeg });
|
||||
setSegTrab(false);
|
||||
if (!r.ok) {
|
||||
setSegError(r.error);
|
||||
return;
|
||||
}
|
||||
huboCambio.current = true;
|
||||
setSeg(r);
|
||||
}
|
||||
const cambiarSegTipo = (t) => {
|
||||
setSegTipo(t);
|
||||
const hs = horasLibres({ tipo: t, dia: segDia, hoy, ahoraMin, bloques: hoyBloques });
|
||||
if (t !== "Tarea" && !hs.includes(segHora)) setSegHora(hs.includes("09:00") ? "09:00" : hs[0] || "");
|
||||
};
|
||||
async function deshacerSeguimiento() {
|
||||
setSegTrab(true);
|
||||
setSegError("");
|
||||
const r = await deshacerSeguimientoAction(seg.accionId);
|
||||
setSegTrab(false);
|
||||
if (!r.ok) {
|
||||
setSegError(r.error);
|
||||
return;
|
||||
}
|
||||
setSegDeshecho(true);
|
||||
}
|
||||
const puedeSeguir = hecho && hecho.accion === "completar" && !deshecho && det?.tieneOpp;
|
||||
// «Hoy, más tarde»: solo si hoy es hábil y todavía queda lugar (llamada/visita: alguna hora libre; tarea: antes de su vencimiento).
|
||||
const hoyHabil = !!hoy && esHabil(hoy);
|
||||
const hoyCupo = hoyHabil && (segTipo === "Tarea" ? ahoraMin < AGENDADOR.horaTarea : horasLibres({ tipo: segTipo, dia: hoy, hoy, ahoraMin, bloques: hoyBloques }).length > 0)
|
||||
&& (det?.hoyAgenda?.cuenta?.[segTipo] ?? 0) < AGENDADOR.topes[segTipo];
|
||||
const TXT_SIN_OPP = "No se ofrece programar un seguimiento desde aquí: esta actividad no está ligada a una oportunidad (su «Referente a» es una cuenta o un caso). Puedes agendarlo desde el Agendador o en Dynamics.";
|
||||
|
||||
// Campos del seguimiento: se usan antes de completar (un solo botón) y después (para reintentar o añadirlo).
|
||||
const camposSeguimiento = () => (
|
||||
<>
|
||||
<div className="gst-lbl">Siguiente actividad</div>
|
||||
<div className="gst-chips">
|
||||
{["Llamada", "Cita", "Tarea"].map((t) => (
|
||||
<button key={t} type="button" className={`gst-chip${segTipo === t ? " on" : ""}`} onClick={() => cambiarSegTipo(t)}>{t === "Cita" ? "Visita" : t}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="gst-lbl">Objetivo</div>
|
||||
<div className="gst-chips">
|
||||
<select className="gst-in" value={segObj} onChange={(e) => setSegObj(e.target.value)}>
|
||||
<option value="">Elige un objetivo…</option>
|
||||
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="gst-lbl">Fecha (lunes a viernes)</div>
|
||||
<div className="gst-chips">
|
||||
{hoyHabil && (
|
||||
<button type="button" className={`gst-chip${segDia === hoy ? " on" : ""}`} disabled={!hoyCupo} title={hoyCupo ? "" : "Ya no quedan horas hoy"} onClick={() => setSegDia(hoy)}>
|
||||
{hoyCupo ? "Hoy, más tarde" : "Hoy: ya no quedan horas"}
|
||||
</button>
|
||||
)}
|
||||
{[["Mañana", addDays(hoy, 1)], ["En 2 días", addDays(hoy, 2)], ["En 3 días", addDays(hoy, 3)], ["Lunes", proximoLunes(hoy)]].map(([l, v]) => (
|
||||
<button key={l} type="button" className={`gst-chip${segDia === v ? " on" : ""}`} onClick={() => setSegDia(v)}>{l}</button>
|
||||
))}
|
||||
<input type="date" className="gst-in" value={segDia} min={hoy} max={addDays(hoy, 30)} onChange={(e) => setSegDia(e.target.value)} />
|
||||
</div>
|
||||
{segDiaMalo && <p className="gst-err">Elige un día hábil: el seguimiento no se agenda en sábado ni en domingo.</p>}
|
||||
{segTipo !== "Tarea" && (
|
||||
<>
|
||||
<div className="gst-lbl">Hora</div>
|
||||
<div className="gst-chips">
|
||||
<select className="gst-in" value={horaSeg} onChange={(e) => setSegHora(e.target.value)}>
|
||||
{horasSeg.map((h) => <option key={h} value={h}>{h}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{segSinHoras && !segDiaMalo && <p className="gst-err">{segDia === hoy ? "Ya no quedan horas libres hoy para esto. Elige otro día." : "No hay horas disponibles ese día."}</p>}
|
||||
{segDia && !segDiaMalo && !segSinHoras && <p className="gst-res">Se agenda: <strong>{segTipo === "Cita" ? "Visita" : segTipo} · {etiqueta(segDia)}{segTipo !== "Tarea" ? ` · ${horaSeg}` : " (vence a las 16:00)"}</strong></p>}
|
||||
{segError && <p className="gst-err">{segError}</p>}
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button type="button" className={className} title={title} onClick={abrir}>
|
||||
{children}
|
||||
</button>
|
||||
{abierto && typeof document !== "undefined" && createPortal(
|
||||
<div className="gst-bd" onClick={cerrar}>
|
||||
<div className="gst" role="dialog" aria-modal="true" aria-label="Gestionar actividad" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="gst-h">
|
||||
<div>
|
||||
<div className="gst-t">{a.tipo} · {clienteDe(a) || det?.asunto || a.asunto}</div>
|
||||
<div className="gst-s">
|
||||
{(oportunidadDe(a) || det?.referente) ? `${oportunidadDe(a) || det.referente} · ` : ""}{det?.asunto && clienteDe(a) ? `${det.asunto} · ` : ""}
|
||||
{det?.scheduledend ? `Para el ${det.scheduledend.slice(0, 10).split("-").reverse().join("/")}` : ""}
|
||||
{det?.owner ? ` · ${det.owner}` : ""}
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="gst-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
|
||||
</div>
|
||||
|
||||
{carga === "cargando" && <p className="gst-msg">Cargando desde Dynamics…</p>}
|
||||
{carga === "error" && <p className="gst-err">{error}</p>}
|
||||
{carga === "apagado" && <p className="gst-err">La gestión de actividades está en pausa por mantenimiento. Mientras tanto, <a href={crm} target="_blank" rel="noopener">ábrela en Dynamics</a>.</p>}
|
||||
|
||||
{carga === "listo" && det && !hecho && (
|
||||
<>
|
||||
{det.enNombreDeOtro && <p className="gst-aviso">Estás actuando en nombre de {det.owner}.</p>}
|
||||
{cerrada ? (
|
||||
<p className="gst-msg">Esta actividad ya está {det.estado}. <a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a></p>
|
||||
) : (
|
||||
<>
|
||||
<div className="gst-ya">
|
||||
<div className="gst-ya-t">Ya registrado</div>
|
||||
<div><b>Objetivo:</b> {det.objetivo || "—"}{a.tipo !== "Tarea" && <> · <b>Participantes:</b> {det.participantes?.length ? nombresDe(det.participantes) : "ninguno marcado"}{det.invitados > 0 ? ` · ${det.invitados} invitado${det.invitados === 1 ? "" : "s"}` : ""}</>}</div>
|
||||
{a.tipo === "Cita" && det.lugar && <div><b>Lugar:</b> {det.lugar}</div>}
|
||||
<div className="gst-ya-nota">{det.nota ? <><b>{a.tipo === "Cita" ? "Resultado" : "Nota"}:</b> {det.nota}</> : <span className="gst-ayuda">Sin nota registrada.</span>}</div>
|
||||
</div>
|
||||
<div className="gst-tabs">
|
||||
{[["completar", "✓ Completar"], ["editar", "✎ Editar"], ["reprogramar", "📅 Reprogramar"], ["cancelar", "✕ Cancelar"]].map(([k, l]) => (
|
||||
<button key={k} type="button" className={accion === k ? "on" : ""} onClick={() => { setAccion(k); setConfirma(false); setError(""); }}>{l}</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{bloqueaFecha && (
|
||||
<p className="gst-aviso">
|
||||
Esta cita tiene {det.invitados} invitado{det.invitados === 1 ? "" : "s"}. Para no enviarles avisos por error, {accion === "cancelar" ? "cancélala" : "reprográmala"} directamente en Dynamics.{" "}
|
||||
<a href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{accion === "reprogramar" && !bloqueaFecha && (
|
||||
<div className="gst-sec">
|
||||
<div className="gst-lbl">Nueva fecha</div>
|
||||
<div className="gst-chips">
|
||||
{rapidos.map(([l, v]) => (
|
||||
<button key={l} type="button" className={`gst-chip${dia === v ? " on" : ""}`} onClick={() => setDia(v)}>{l}</button>
|
||||
))}
|
||||
<input type="date" className="gst-in" value={dia} min={hoy} max={addDays(hoy, 30)} onChange={(e) => setDia(e.target.value)} />
|
||||
</div>
|
||||
{!esTarea && (
|
||||
<>
|
||||
<div className="gst-lbl">Hora</div>
|
||||
<div className="gst-chips">
|
||||
{HORAS.filter((h) => dia !== hoy || horaAMin(h) >= ahoraMin + 5).map((h) => (
|
||||
<button key={h} type="button" className={`gst-chip${hora === h ? " on" : ""}`} onClick={() => setHora(h)}>{h}</button>
|
||||
))}
|
||||
<input type="time" className="gst-in" value={hora} min={dia === hoy ? minAHora(ahoraMin) : undefined} onChange={(e) => setHora(e.target.value)} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{horaPasada && <p className="gst-err">Esa hora ya pasó. Elige una hora más tarde o cambia el día.</p>}
|
||||
{dia && <p className="gst-res">Nueva fecha: <strong>{etiqueta(dia)}{!esTarea && hora ? ` · ${hora}` : ""}</strong>{esTarea ? " (vence a las 16:00)" : ""}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accion === "editar" && (
|
||||
<div className="gst-sec">
|
||||
<div className="gst-lbl">Objetivo</div>
|
||||
<div className="gst-chips">
|
||||
<select className="gst-in" value={objEd} onChange={(e) => setObjEd(e.target.value)}>
|
||||
<option value="">Sin cambio</option>
|
||||
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{a.tipo !== "Tarea" && !conInvitados && (
|
||||
<>
|
||||
<div className="gst-lbl">Duración</div>
|
||||
<div className="gst-chips">
|
||||
{(a.tipo === "Cita" ? [30, 60, 90, 120] : [10, 15, 30, 45, 60]).map((m) => (
|
||||
<button key={m} type="button" className={`gst-chip${durEd === m ? " on" : ""}`} onClick={() => setDurEd(m)}>{m} min</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{a.tipo === "Cita" && conInvitados && <p className="gst-ayuda">Esta visita tiene invitados: su duración se cambia en Dynamics para no enviarles avisos por error.</p>}
|
||||
{a.tipo !== "Tarea" ? (
|
||||
<>
|
||||
<div className="gst-lbl">¿Quién participará?</div>
|
||||
<div className="gst-chips">
|
||||
{ROLES.map((r) => (
|
||||
<button key={r.codigo} type="button" className={`gst-chip${rolesEd.includes(r.codigo) ? " on" : ""}`} aria-pressed={rolesEd.includes(r.codigo)}
|
||||
onClick={() => setRolesEd((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo]))}>{r.nombre}</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="gst-ayuda">Se guarda en la {a.tipo === "Cita" ? "visita" : "llamada"}. La oportunidad se actualiza cuando la completes.</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="gst-ayuda">Las tareas no llevan participantes.</p>
|
||||
)}
|
||||
<div className="gst-lbl">Agregar una nota (se suma arriba de lo anterior)</div>
|
||||
<textarea className="gst-ta" rows={3} maxLength={1500} value={notaEd} placeholder="Ej.: Llevar la propuesta actualizada" onChange={(e) => setNotaEd(e.target.value)} />
|
||||
<p className="gst-ayuda">El asunto, la descripción y los invitados no se editan aquí: se hacen en Dynamics o en Outlook.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(accion === "completar" || accion === "cancelar") && !bloqueaFecha && (
|
||||
<div className="gst-sec">
|
||||
<div className="gst-lbl">{accion === "completar" ? "Nota breve: qué pasó y qué sigue" : "Motivo (opcional)"}</div>
|
||||
<textarea
|
||||
className="gst-ta"
|
||||
rows={3}
|
||||
maxLength={1500}
|
||||
value={nota}
|
||||
placeholder={accion === "completar" ? "Ej.: Habló con el gerente, pidió ajustar la oferta" : "Ej.: El cliente ya no está interesado"}
|
||||
onChange={(e) => { setNota(e.target.value); setConfirma(false); }}
|
||||
/>
|
||||
{accion === "completar" && (
|
||||
<div className="gst-chips">
|
||||
{(FRASES[a.tipo] || []).map((f) => (
|
||||
<button key={f} type="button" className="gst-chip" onClick={() => fraseDe(f)}>{f}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{a.tipo === "Cita" && <p className="gst-ayuda">La nota se guarda en «Resultado de la visita». La descripción de la cita (la invitación) no se toca.</p>}
|
||||
{accion === "completar" && (a.tipo === "Cita" || det.tieneOpp) && (
|
||||
<>
|
||||
<div className="gst-lbl">¿Quién participó? (opcional)</div>
|
||||
<div className="gst-chips">
|
||||
{ROLES.map((r) => (
|
||||
<button
|
||||
key={r.codigo}
|
||||
type="button"
|
||||
className={`gst-chip${roles.includes(r.codigo) ? " on" : ""}`}
|
||||
aria-pressed={roles.includes(r.codigo)}
|
||||
onClick={() => { setRoles((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo])); setConfirma(false); }}
|
||||
>
|
||||
{r.nombre}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="gst-ayuda">
|
||||
Gerencia Comercial participa cuando asistió o se involucró (visita, levantamiento, presentación por Teams, llamada de seguimiento).
|
||||
{det.tieneOpp ? " Se suma a la oportunidad; marcar Gerencia Comercial activa «Participación de GV», que suma a su puntuación." : ""}
|
||||
{det.opp && (det.opp.gv || det.opp.participantes.length) ? ` Ya consta en la oportunidad: ${[det.opp.gv ? "Gerencia Comercial" : null, det.opp.participantes.length ? nombresDe(det.opp.participantes) : null].filter(Boolean).join(", ")}.` : ""}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accion === "completar" && !bloqueaFecha && (
|
||||
<div className="gst-sec gst-seg">
|
||||
{!det.tieneOpp ? (
|
||||
<p className="gst-ayuda">{TXT_SIN_OPP}</p>
|
||||
) : !segAbierto ? (
|
||||
<button type="button" className="gst-sec-btn" onClick={() => { setSegAbierto(true); setConfirma(false); }}>+ Programar siguiente seguimiento</button>
|
||||
) : (
|
||||
<>
|
||||
{camposSeguimiento()}
|
||||
<p className="gst-ayuda">Se crea junto con «{textoAccion}». {!segObj ? "Elige un objetivo para poder guardar." : ""}</p>
|
||||
<button type="button" className="gst-link" onClick={() => setSegAbierto(false)}>Quitar el seguimiento</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="gst-err">{error}</p>}
|
||||
{confirma && accion === "completar" && <p className="gst-aviso">No escribiste nota. La nota ayuda a ver el historial de la oportunidad. ¿Completar sin nota?</p>}
|
||||
{confirma && accion === "cancelar" && <p className="gst-aviso">¿Seguro que quieres cancelar esta actividad? Podrás deshacerlo justo después.</p>}
|
||||
|
||||
<div className="gst-pie">
|
||||
<a className="gst-link" href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||||
<button type="button" className="gst-sec-btn" onClick={cerrar}>Cerrar</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`gst-go${accion === "cancelar" ? " pel" : ""}`}
|
||||
disabled={trabajando || bloqueaFecha || (accion === "reprogramar" && (!dia || (!esTarea && !hora) || horaPasada)) || (accion === "completar" && segAbierto && !!det?.tieneOpp && !segListo)}
|
||||
onClick={ejecutar}
|
||||
>
|
||||
{trabajando ? "Guardando…" : confirma ? (accion === "completar" ? "Sí, completar sin nota" : "Sí, cancelar") : textoAccion}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{hecho && (
|
||||
<div className="gst-ok">
|
||||
<p className="gst-okt">
|
||||
{deshecho
|
||||
? "↩ Se deshizo: la actividad volvió a como estaba."
|
||||
: hecho.accion === "completar"
|
||||
? `✓ ${a.tipo === "Cita" ? "Visita" : a.tipo} completada en Dynamics`
|
||||
: hecho.accion === "editar"
|
||||
? "✓ Cambios guardados en Dynamics"
|
||||
: hecho.accion === "cancelar"
|
||||
? "✓ Actividad cancelada en Dynamics"
|
||||
: `✓ Reprogramada para el ${etiqueta(dia)}${!esTarea ? ` a las ${hora}` : ""}`}
|
||||
</p>
|
||||
{!deshecho && hecho.opp?.marcoGV && <p className="gst-ayuda">Se marcó «Participación de GV» en la oportunidad (suma a su puntuación).</p>}
|
||||
{!deshecho && hecho.opp?.roles && <p className="gst-ayuda">Se sumó a la oportunidad: {hecho.opp.roles}.</p>}
|
||||
{!deshecho && hecho.opp?.yaEstaba && <p className="gst-ayuda">La oportunidad ya tenía registrada esa participación.</p>}
|
||||
{hecho.avisoOpp && <p className="gst-aviso">{hecho.avisoOpp}</p>}
|
||||
{hecho.accion === "completar" && !deshecho && !det?.tieneOpp && <p className="gst-ayuda">{TXT_SIN_OPP}</p>}
|
||||
{puedeSeguir && (
|
||||
<div className="gst-seg">
|
||||
{seg && !segDeshecho ? (
|
||||
<p className="gst-okt">✓ Seguimiento creado para el {seg.dia}{seg.hora ? ` ${seg.hora}` : ""} · {seg.tipo === "Cita" ? "Visita" : seg.tipo}{" "}
|
||||
<button type="button" className="gst-link" disabled={segTrab} onClick={deshacerSeguimiento}>{segTrab ? "…" : "↩ Deshacer"}</button>
|
||||
</p>
|
||||
) : segDeshecho ? (
|
||||
<p className="gst-ayuda">↩ Se canceló el seguimiento que acababas de programar.</p>
|
||||
) : !segAbierto ? (
|
||||
<button type="button" className="gst-sec-btn" onClick={() => setSegAbierto(true)}>+ Programar siguiente seguimiento</button>
|
||||
) : (
|
||||
<>
|
||||
{camposSeguimiento()}
|
||||
<button type="button" className="gst-go" disabled={segTrab || !segListo} onClick={guardarSeguimiento}>{segTrab ? "Guardando…" : "Guardar seguimiento"}</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="gst-err">{error}</p>}
|
||||
<div className="gst-pie">
|
||||
<a className="gst-link" href={crm} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||||
{!deshecho && <button type="button" className="gst-sec-btn" disabled={trabajando} onClick={deshacer}>{trabajando ? "…" : "↩ Deshacer"}</button>}
|
||||
<button type="button" className="gst-go" onClick={cerrar}>Listo</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
300
app/components/actividades/NuevaActividad.js
Normal file
300
app/components/actividades/NuevaActividad.js
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
"use client";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { buscarReferentesAction, crearActividadLibreAction } from "../../cuentas/cuentasActions";
|
||||
import { deshacerSeguimientoAction, refrescarPantallasAction } from "../../actividades/gestionActions";
|
||||
import { OBJETIVOS_LIBRES } from "../../lib/agendador";
|
||||
import { ROLES } from "../../lib/participantes";
|
||||
import { addDays } from "../../lib/plan";
|
||||
|
||||
// Ventana para CREAR una actividad (llamada, visita o tarea) a una fecha y hora, ligada a una oportunidad o a
|
||||
// una cuenta que se busca por nombre. Se abre desde el calendario de la Agenda (clic en una franja) y desde la
|
||||
// ficha de la cuenta. Misma apariencia y «Deshacer» que la ventana de gestionar actividades.
|
||||
|
||||
const DIAS = ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
|
||||
const MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||||
const etiqueta = (iso) => {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
return `${DIAS[new Date(`${iso}T12:00:00Z`).getUTCDay()]} ${d} ${MESES[m - 1]}`;
|
||||
};
|
||||
const DUR = { Llamada: [15, 30, 45, 60], Cita: [30, 60, 90, 120] };
|
||||
const FRASES = {
|
||||
Llamada: ["No contestó", "Dejé mensaje", "Habló con el decisor", "Interesado", "Pidió propuesta", "Llamar de nuevo"],
|
||||
Cita: ["Visita realizada", "Se presentó la oferta", "Pidió ajustes", "Pasan a revisión interna", "Se definió fecha de firma"],
|
||||
Tarea: ["Oferta enviada", "Contrato elaborado", "Seguimiento realizado", "Pendiente de respuesta del cliente"],
|
||||
};
|
||||
const TIPOS = [["Llamada", "📞 Llamada"], ["Cita", "🤝 Visita"], ["Tarea", "☑ Tarea"]];
|
||||
|
||||
// Recordatorio al agendar una visita virtual: la app NO crea la reunión de Teams ni envía invitaciones (decisión de Marco, 2026-11-10).
|
||||
function RecordatorioTeams() {
|
||||
return (
|
||||
<div className="gst-teams" role="note">
|
||||
<b>Reunión virtual:</b> esta visita todavía no tiene enlace de Teams ni invitación.
|
||||
<ol>
|
||||
<li>Ábrela en Outlook (o con «Abrir en Dynamics») y agrega la reunión de Teams.</li>
|
||||
<li>Agrega a tus contactos como invitados.</li>
|
||||
<li>Envía la invitación.</li>
|
||||
</ol>
|
||||
Hasta entonces, el cliente no recibe nada.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// preset: { dia, hora, referente?: { tipo: "opportunity" | "account", id, nombre } }
|
||||
export default function NuevaActividad({ hoy, preset, onClose }) {
|
||||
const router = useRouter();
|
||||
const [tipo, setTipo] = useState("Llamada");
|
||||
const [ref, setRef] = useState(preset.referente || null);
|
||||
const [q, setQ] = useState("");
|
||||
const [res, setRes] = useState(null); // { opps, cuentas } | null
|
||||
const [buscando, setBuscando] = useState(false);
|
||||
const [objetivo, setObjetivo] = useState(preset.objetivo || "");
|
||||
const [dia, setDia] = useState(preset.dia || hoy);
|
||||
const [hora, setHora] = useState(preset.hora || "09:00");
|
||||
const [dur, setDur] = useState(30);
|
||||
const [error, setError] = useState("");
|
||||
const [trabajando, setTrabajando] = useState(false);
|
||||
const [realizada, setRealizada] = useState(!!preset.realizada); // «ya la hice»: se crea y se completa de una vez
|
||||
const [nota, setNota] = useState("");
|
||||
const [roles, setRoles] = useState([]);
|
||||
const [modalidad, setModalidad] = useState("presencial"); // solo visitas: define el lugar (Oficina del cliente / Virtual)
|
||||
const [hecho, setHecho] = useState(null);
|
||||
const [deshecho, setDeshecho] = useState(false);
|
||||
const huboCambio = useRef(false);
|
||||
const seq = useRef(0);
|
||||
|
||||
// Búsqueda con pequeña espera para no consultar Dynamics en cada tecla.
|
||||
useEffect(() => {
|
||||
const t = q.trim();
|
||||
if (t.length < 2) {
|
||||
setRes(null);
|
||||
return;
|
||||
}
|
||||
const mi = ++seq.current;
|
||||
setBuscando(true);
|
||||
const h = setTimeout(async () => {
|
||||
const r = await buscarReferentesAction(t);
|
||||
if (mi !== seq.current) return;
|
||||
setBuscando(false);
|
||||
if (r.ok) setRes(r);
|
||||
else { setRes(null); setError(r.error); }
|
||||
}, 350);
|
||||
return () => clearTimeout(h);
|
||||
}, [q]);
|
||||
|
||||
useEffect(() => {
|
||||
setDur(tipo === "Cita" ? 60 : 30);
|
||||
}, [tipo]);
|
||||
|
||||
async function cerrar() {
|
||||
if (huboCambio.current) {
|
||||
huboCambio.current = false;
|
||||
await refrescarPantallasAction();
|
||||
router.refresh();
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
|
||||
async function crear() {
|
||||
setTrabajando(true);
|
||||
setError("");
|
||||
const r = await crearActividadLibreAction({ tipo, referenteTipo: ref.tipo, referenteId: ref.id, objetivo, dia, hora, duracion: dur, realizada, nota, participantes: tipo === "Tarea" ? [] : roles, enNombreDe: !!preset.enNombreDe, modalidad });
|
||||
setTrabajando(false);
|
||||
if (!r.ok) {
|
||||
setError(r.error);
|
||||
return;
|
||||
}
|
||||
huboCambio.current = true;
|
||||
setHecho(r);
|
||||
}
|
||||
|
||||
async function deshacer() {
|
||||
setTrabajando(true);
|
||||
setError("");
|
||||
const r = await deshacerSeguimientoAction(hecho.accionId);
|
||||
setTrabajando(false);
|
||||
if (!r.ok) {
|
||||
setError(r.error);
|
||||
return;
|
||||
}
|
||||
setDeshecho(true);
|
||||
}
|
||||
|
||||
const listo = ref && objetivo && dia && hora;
|
||||
const min = realizada ? addDays(hoy, -30) : hoy;
|
||||
const max = realizada ? hoy : addDays(hoy, 30);
|
||||
const alternar = (v) => {
|
||||
setRealizada(v);
|
||||
// Al cambiar de modo, la fecha vuelve a hoy (siempre válida en los dos).
|
||||
setDia(hoy);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="gst-bd" onClick={cerrar}>
|
||||
<div className="gst" role="dialog" aria-modal="true" aria-label="Nueva actividad" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="gst-h">
|
||||
<div>
|
||||
<div className="gst-t">Nueva actividad</div>
|
||||
<div className="gst-s">{etiqueta(dia)} · {hora}{realizada ? " · ya realizada" : ""}</div>
|
||||
</div>
|
||||
<button type="button" className="gst-x" aria-label="Cerrar" onClick={cerrar}>✕</button>
|
||||
</div>
|
||||
|
||||
{hecho ? (
|
||||
<div className="gst-ok">
|
||||
<p className="gst-okt">{deshecho ? "↩ Se canceló la actividad que acabas de crear." : hecho.completada ? `✓ Registrada como completada en Dynamics: ${hecho.asunto}` : `✓ Creada en Dynamics: ${hecho.asunto}`}</p>
|
||||
{!deshecho && tipo === "Cita" && modalidad === "virtual" && <RecordatorioTeams />}
|
||||
{!deshecho && <p className="gst-ayuda">{TIPOS.find((t) => t[0] === tipo)?.[1].replace(/^\S+ /, "")} el {etiqueta(dia)}{tipo !== "Tarea" ? ` a las ${hora}` : ` (vence a las ${hora})`}. Ya aparece en tu agenda.</p>}
|
||||
{hecho.avisoOpp && <p className="gst-aviso">{hecho.avisoOpp}</p>}
|
||||
{error && <p className="gst-err">{error}</p>}
|
||||
<div className="gst-pie">
|
||||
{!deshecho && !hecho.completada && <button type="button" className="gst-sec-btn" disabled={trabajando} onClick={deshacer}>{trabajando ? "…" : "↩ Deshacer"}</button>}
|
||||
<button type="button" className="gst-go" onClick={cerrar}>Listo</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="gst-tabs">
|
||||
{TIPOS.map(([k, l]) => (
|
||||
<button key={k} type="button" className={tipo === k ? "on" : ""} onClick={() => setTipo(k)}>{l}</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="gst-sec">
|
||||
<div className="gst-lbl">¿Para qué oportunidad o cuenta?</div>
|
||||
{ref && (
|
||||
<div className="gst-ref">
|
||||
<span><b>{ref.tipo === "opportunity" ? "Oportunidad" : "Cuenta"}:</b> {ref.nombre}</span>
|
||||
{!preset.referente && <button type="button" className="gst-link" onClick={() => { setRef(null); setQ(""); }}>Cambiar</button>}
|
||||
</div>
|
||||
)}
|
||||
{ref && preset.referente && preset.opciones?.length > 0 && (
|
||||
<div className="gst-chips" style={{ marginTop: 8 }}>
|
||||
<select
|
||||
className="gst-in"
|
||||
value={ref.tipo === "account" ? "account" : ref.id}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (v === "account") setRef(preset.referente);
|
||||
else setRef({ tipo: "opportunity", id: v, nombre: preset.opciones.find((o) => o.id === v)?.nombre || "" });
|
||||
}}
|
||||
>
|
||||
<option value="account">Ligar a la cuenta</option>
|
||||
{preset.opciones.map((o) => <option key={o.id} value={o.id}>Ligar a la oportunidad: {o.nombre}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{!ref && (
|
||||
<>
|
||||
<input className="gst-in gst-busca" autoFocus value={q} placeholder="Escribe el nombre de la oportunidad o del cliente…" onChange={(e) => setQ(e.target.value)} />
|
||||
{buscando && <p className="gst-ayuda">Buscando en Dynamics…</p>}
|
||||
{res && !buscando && (
|
||||
<div className="gst-res-lista">
|
||||
{res.opps.length > 0 && <div className="gst-grp">Oportunidades abiertas</div>}
|
||||
{res.opps.map((o) => (
|
||||
<button type="button" key={o.id} className="gst-opt" onClick={() => setRef({ tipo: "opportunity", id: o.id, nombre: o.cliente ? `${o.cliente} — ${o.nombre}` : o.nombre })}>
|
||||
<b>{o.cliente || o.nombre}</b>
|
||||
<span>{o.nombre}{o.propietario ? ` · ${o.propietario}` : ""}</span>
|
||||
</button>
|
||||
))}
|
||||
{res.cuentas.length > 0 && <div className="gst-grp">Cuentas</div>}
|
||||
{res.cuentas.map((c) => (
|
||||
<button type="button" key={c.id} className="gst-opt" onClick={() => setRef({ tipo: "account", id: c.id, nombre: c.nombre })}>
|
||||
<b>{c.nombre}</b>
|
||||
<span>{[c.tipo, c.propietario].filter(Boolean).join(" · ")}</span>
|
||||
</button>
|
||||
))}
|
||||
{!res.opps.length && !res.cuentas.length && <p className="gst-ayuda">Sin coincidencias. Prueba con otra parte del nombre.</p>}
|
||||
</div>
|
||||
)}
|
||||
{!res && q.trim().length < 2 && <p className="gst-ayuda">Escribe al menos 2 letras.</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="gst-sec">
|
||||
<div className="gst-lbl">Objetivo</div>
|
||||
<div className="gst-chips">
|
||||
<select className="gst-in" value={objetivo} onChange={(e) => setObjetivo(e.target.value)}>
|
||||
<option value="">Elige un objetivo…</option>
|
||||
{OBJETIVOS_LIBRES.map((o) => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="gst-lbl">Fecha y hora</div>
|
||||
<div className="gst-chips">
|
||||
<input type="date" className="gst-in" value={dia} min={min} max={max} onChange={(e) => setDia(e.target.value)} />
|
||||
<input type="time" className="gst-in" value={hora} step={900} onChange={(e) => setHora(e.target.value)} />
|
||||
</div>
|
||||
{tipo !== "Tarea" && (
|
||||
<>
|
||||
<div className="gst-lbl">Duración</div>
|
||||
<div className="gst-chips">
|
||||
{DUR[tipo].map((m) => (
|
||||
<button key={m} type="button" className={`gst-chip${dur === m ? " on" : ""}`} onClick={() => setDur(m)}>{m} min</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{tipo === "Tarea" && !realizada && <p className="gst-ayuda">La tarea vence a la hora indicada.</p>}
|
||||
{tipo === "Cita" && (
|
||||
<>
|
||||
<div className="gst-lbl">Modalidad</div>
|
||||
<div className="gst-chips">
|
||||
<button type="button" className={`gst-chip${modalidad === "presencial" ? " on" : ""}`} onClick={() => setModalidad("presencial")}>Presencial</button>
|
||||
<button type="button" className={`gst-chip${modalidad === "virtual" ? " on" : ""}`} onClick={() => setModalidad("virtual")}>Virtual</button>
|
||||
</div>
|
||||
{modalidad === "presencial" ? (
|
||||
<p className="gst-ayuda">El lugar se guarda como «Oficina del cliente». Si conoces la dirección, cámbiala en Dynamics o en Outlook; si no, déjalo así.</p>
|
||||
) : (
|
||||
<RecordatorioTeams />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{tipo !== "Tarea" && !realizada && (
|
||||
<>
|
||||
<div className="gst-lbl">¿Quién participará? (opcional)</div>
|
||||
<div className="gst-chips">
|
||||
{ROLES.map((r) => (
|
||||
<button key={r.codigo} type="button" className={`gst-chip${roles.includes(r.codigo) ? " on" : ""}`} aria-pressed={roles.includes(r.codigo)}
|
||||
onClick={() => setRoles((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo]))}>{r.nombre}</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="gst-ayuda">Se guarda en la {tipo === "Cita" ? "visita" : "llamada"}; la oportunidad se actualiza cuando la completes.</p>
|
||||
</>
|
||||
)}
|
||||
<label className="gst-check">
|
||||
<input type="checkbox" checked={realizada} onChange={(e) => alternar(e.target.checked)} /> Ya la realicé: registrar el resultado ahora
|
||||
</label>
|
||||
{realizada && (
|
||||
<>
|
||||
<div className="gst-lbl">Resultado: qué pasó y qué sigue</div>
|
||||
<textarea className="gst-ta" rows={3} maxLength={1500} value={nota} placeholder="Ej.: Habló con el gerente, pidió ajustar la oferta" onChange={(e) => setNota(e.target.value)} />
|
||||
<div className="gst-chips">
|
||||
{(FRASES[tipo] || []).map((f) => (
|
||||
<button key={f} type="button" className="gst-chip" onClick={() => setNota((n) => (n.trim() ? `${n.trim()}. ${f}` : f))}>{f}</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="gst-lbl">¿Quién participó? (opcional)</div>
|
||||
<div className="gst-chips">
|
||||
{ROLES.map((r) => (
|
||||
<button key={r.codigo} type="button" className={`gst-chip${roles.includes(r.codigo) ? " on" : ""}`} aria-pressed={roles.includes(r.codigo)}
|
||||
onClick={() => setRoles((x) => (x.includes(r.codigo) ? x.filter((c) => c !== r.codigo) : [...x, r.codigo]))}>{r.nombre}</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="gst-ayuda">Se crea y se completa en un solo paso, con la fecha y hora que indiques (hoy o hasta 30 días atrás). Una vez completada ya no se puede deshacer desde aquí.</p>
|
||||
</>
|
||||
)}
|
||||
{tipo === "Cita" && <p className="gst-ayuda">La visita se crea sin invitados ni descripción: nada se envía a ningún cliente. Agrega invitados, si hace falta, en Dynamics.</p>}
|
||||
</div>
|
||||
|
||||
{error && <p className="gst-err">{error}</p>}
|
||||
<div className="gst-pie">
|
||||
<button type="button" className="gst-sec-btn" onClick={cerrar}>Cancelar</button>
|
||||
<button type="button" className="gst-go" disabled={trabajando || !listo} onClick={crear}>{trabajando ? "Guardando…" : realizada ? "Registrar como completada" : "Crear actividad"}</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
app/components/actividades/NuevaActividadBoton.js
Normal file
21
app/components/actividades/NuevaActividadBoton.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
"use client";
|
||||
import { useState } from "react";
|
||||
import NuevaActividad from "./NuevaActividad";
|
||||
|
||||
// Botón «Agregar actividad» de la ficha de una cuenta: abre la ventana ya ligada a esa cuenta. Si la cuenta
|
||||
// tiene oportunidades abiertas, la ventana deja elegir si la actividad va a la cuenta o a una de ellas.
|
||||
export default function NuevaActividadBoton({ hoy, referente, oportunidades = [] }) {
|
||||
const [abierto, setAbierto] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button type="button" className="gst-go" style={{ padding: "8px 16px" }} onClick={() => setAbierto(true)}>+ Agregar actividad</button>
|
||||
{abierto && (
|
||||
<NuevaActividad
|
||||
hoy={hoy}
|
||||
preset={{ referente, dia: hoy, hora: "09:00", opciones: oportunidades }}
|
||||
onClose={() => setAbierto(false)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
390
app/components/agenda/AgendaClient.js
Normal file
390
app/components/agenda/AgendaClient.js
Normal file
|
|
@ -0,0 +1,390 @@
|
|||
"use client";
|
||||
import { useState, useMemo } from "react";
|
||||
import { actAncla, actEstadoFinal } from "../../lib/derive";
|
||||
import GestionarActividad from "../actividades/GestionarActividad";
|
||||
import NuevaActividad from "../actividades/NuevaActividad";
|
||||
import { localDeIso } from "../../lib/agendador";
|
||||
import { hoyManagua, addDays } from "../../lib/plan";
|
||||
import { clienteDe, oportunidadDe, tooltipDe } from "../../lib/agendaVista";
|
||||
|
||||
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}`;
|
||||
}
|
||||
|
||||
// Calendario tipo Outlook: la semana en columnas con horas de 7:00 a 19:00. Clic en una franja vacía = nueva
|
||||
// actividad a esa hora; clic en una actividad = completarla, reprogramarla o cancelarla.
|
||||
const CAL_INI = 420; // 7:00
|
||||
const CAL_FIN = 1140; // 19:00
|
||||
const CAL_PX = 40; // alto de cada media hora (cabe cliente + oportunidad)
|
||||
const ICONO = { Llamada: "📞", Cita: "🤝", Tarea: "☑" };
|
||||
const hhmm = (m) => `${pad(Math.floor(m / 60))}:${pad(m % 60)}`;
|
||||
|
||||
// Instante de inicio con que se dibuja: llamadas y visitas empiezan en `scheduledstart`; la tarea vence en `scheduledend`.
|
||||
const inicioDe = (a) => (a.tipo === "Tarea" ? a.scheduledend || a.scheduledstart : a.scheduledstart || a.scheduledend);
|
||||
|
||||
function bloquesDelDia(items) {
|
||||
// Posición vertical según hora y duración; las que se encimen se reparten en carriles.
|
||||
const bl = items
|
||||
.map((a) => {
|
||||
const ini = localDeIso(inicioDe(a));
|
||||
const finIso = a.tipo === "Tarea" ? null : a.scheduledend;
|
||||
const fin = finIso ? localDeIso(finIso) : null;
|
||||
const m0 = Math.min(Math.max(ini.min, CAL_INI), CAL_FIN - 30);
|
||||
let dur = fin && fin.dia === ini.dia && fin.min > ini.min ? fin.min - ini.min : 30;
|
||||
dur = Math.max(dur, 30);
|
||||
return { a, m0, m1: Math.min(m0 + dur, CAL_FIN) };
|
||||
})
|
||||
.sort((x, y) => x.m0 - y.m0 || x.m1 - y.m1);
|
||||
const carriles = [];
|
||||
for (const b of bl) {
|
||||
let c = carriles.findIndex((fin) => fin <= b.m0);
|
||||
if (c === -1) { c = carriles.length; carriles.push(0); }
|
||||
carriles[c] = b.m1;
|
||||
b.carril = c;
|
||||
}
|
||||
bl.forEach((b) => { b.total = carriles.length; });
|
||||
return bl;
|
||||
}
|
||||
|
||||
function Item({ a }) {
|
||||
const venc = a.estadoFinal === "Vencida";
|
||||
const hecha = a.estadoFinal === "Completada";
|
||||
const ref = clienteDe(a) || a.asunto || "—";
|
||||
const sub = [];
|
||||
if (oportunidadDe(a)) sub.push(oportunidadDe(a));
|
||||
sub.push(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 (
|
||||
// Un clic abre la ventana para completar, reprogramar o cancelar sin salir del informe (dentro hay
|
||||
// un enlace «Abrir en Dynamics»).
|
||||
<GestionarActividad
|
||||
a={a}
|
||||
className={`ag-item t-${a.tipo.toLowerCase()}${venc ? " venc" : ""}${hecha ? " hecha" : ""}`}
|
||||
title={tooltipDe(a)}
|
||||
>
|
||||
<span className="ag-item-t">{a.tipo} · {ref}</span>
|
||||
<span className="ag-item-s">{sub.join(" · ")}</span>
|
||||
</GestionarActividad>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AgendaClient({ actividades }) {
|
||||
const [vista, setVista] = useState("calendario");
|
||||
const [nueva, setNueva] = useState(null); // { dia, hora } al hacer clic en una franja
|
||||
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 !== "mes") next.setDate(next.getDate() + d * 7);
|
||||
else next.setMonth(next.getMonth() + d);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
let cuerpo, lbl;
|
||||
if (vista === "calendario") {
|
||||
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 = hoyManagua();
|
||||
const ahoraMin = localDeIso(new Date().toISOString()).min;
|
||||
const slots = Array.from({ length: (CAL_FIN - CAL_INI) / 30 }, (_, i) => CAL_INI + i * 30);
|
||||
const alto = slots.length * CAL_PX;
|
||||
const sinHora = list.filter((a) => !(a.scheduledstart || a.scheduledend));
|
||||
cuerpo = (
|
||||
<>
|
||||
<p className="hint" style={{ margin: "0 0 8px" }}>Haz clic en una franja vacía para agendar una actividad (en una franja ya pasada, para registrar una que ya hiciste); clic en una actividad para completarla, reprogramarla o cancelarla.</p>
|
||||
<div className="cal">
|
||||
<div className="cal-head">
|
||||
<div className="cal-corner" />
|
||||
{dias.map((d, i) => (
|
||||
<div className={`cal-dh${iso(d) === hoy ? " hoy" : ""}`} key={iso(d)}>{AG_DIAS[i]} {d.getDate()} {AG_MESES[d.getMonth()]}</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="cal-body" style={{ height: alto }}>
|
||||
<div className="cal-horas">
|
||||
{slots.map((m, i) => (
|
||||
<div key={m} className="cal-h" style={{ height: CAL_PX }}>{i % 2 === 0 ? hhmm(m) : ""}</div>
|
||||
))}
|
||||
</div>
|
||||
{dias.map((d) => {
|
||||
const diso = iso(d);
|
||||
const delDia = list.filter((a) => {
|
||||
const ref = inicioDe(a);
|
||||
return ref && localDeIso(ref).dia === diso;
|
||||
});
|
||||
const bl = bloquesDelDia(delDia);
|
||||
const pasado = (m) => diso < hoy || (diso === hoy && m + 30 <= ahoraMin);
|
||||
return (
|
||||
<div className={`cal-col${diso === hoy ? " hoy" : ""}`} key={diso}>
|
||||
{slots.map((m) => (
|
||||
<div
|
||||
key={m}
|
||||
className={`cal-slot${m % 60 === 0 ? " hh" : ""}${pasado(m) ? " pasado" : ""}`}
|
||||
style={{ height: CAL_PX }}
|
||||
title={pasado(m) ? `Registrar una actividad ya realizada (${hhmm(m)})` : `Agendar ${hhmm(m)}`}
|
||||
onClick={() => setNueva({ dia: diso, hora: hhmm(m), realizada: pasado(m) })}
|
||||
/>
|
||||
))}
|
||||
{bl.map((b) => (
|
||||
<div
|
||||
key={b.a.id}
|
||||
className="cal-ev"
|
||||
style={{
|
||||
top: ((b.m0 - CAL_INI) / 30) * CAL_PX + 1,
|
||||
height: Math.max(((b.m1 - b.m0) / 30) * CAL_PX - 2, 24),
|
||||
left: `calc(${(b.carril / b.total) * 100}% + 2px)`,
|
||||
width: `calc(${100 / b.total}% - 4px)`,
|
||||
}}
|
||||
>
|
||||
<GestionarActividad
|
||||
a={b.a}
|
||||
className={`ag-item cal-it t-${b.a.tipo.toLowerCase()}${b.a.estadoFinal === "Vencida" ? " venc" : ""}${b.a.estadoFinal === "Completada" ? " hecha" : ""}${b.total >= 4 ? " apretado" : ""}`}
|
||||
title={tooltipDe(b.a, hhmm(b.m0))}
|
||||
>
|
||||
<span className="ag-item-t">{hhmm(b.m0)} {ICONO[b.a.tipo]} {clienteDe(b.a) || b.a.asunto || "—"}</span>
|
||||
{oportunidadDe(b.a) && <span className="cal-opp">{oportunidadDe(b.a)}</span>}
|
||||
</GestionarActividad>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{sinHora.length > 0 && <p className="hint">{sinHora.length} actividad{sinHora.length === 1 ? "" : "es"} sin hora no se dibuja{sinHora.length === 1 ? "" : "n"} aquí; véalas en «Lista semanal».</p>}
|
||||
</>
|
||||
);
|
||||
} else 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();
|
||||
const hoyM = hoyManagua();
|
||||
// Cuadro «+» de cada día (lunes a sábado): un día pasado abre la ventana en modo «Ya la realicé»; hoy o futuro,
|
||||
// propone la próxima hora en punto (o las 9:00 en otro día).
|
||||
const presetDia = (diso) => {
|
||||
if (diso < hoyM) return { dia: diso, hora: "09:00", realizada: true };
|
||||
let hora = "09:00";
|
||||
if (diso === hoyM) {
|
||||
const sig = Math.ceil((localDeIso(new Date().toISOString()).min + 1) / 60) * 60;
|
||||
hora = hhmm(Math.min(Math.max(sig, 360), 1200));
|
||||
}
|
||||
return { dia: diso, hora };
|
||||
};
|
||||
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>}
|
||||
{i < 6 && diso >= addDays(hoyM, -30) && (
|
||||
<button
|
||||
type="button"
|
||||
className="ag-add"
|
||||
title={diso < hoyM ? "Registrar una actividad que ya hiciste ese día" : "Agregar una actividad no planificada a este día"}
|
||||
aria-label={`Agregar actividad el ${AG_DIAS[i]} ${d.getDate()}`}
|
||||
onClick={() => setNueva(presetDia(diso))}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
)}
|
||||
</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" style={{ cursor: venc ? "pointer" : "default" }} title={venc ? "Ver las vencidas" : ""} onClick={() => venc && setVista("vencidas")}><span className="n pierde">{venc}</span><span className="l">Vencidas — su fecha ya pasó{venc ? " (clic para verlas)" : ""}</span></div>
|
||||
</div>
|
||||
|
||||
<div className="ag-toolbar">
|
||||
<div className="seg-tabs">
|
||||
{[["calendario", "Calendario"], ["semana", "Lista semanal"], ["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}
|
||||
{nueva && <NuevaActividad hoy={hoyManagua()} preset={nueva} onClose={() => setNueva(null)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
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 90 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>
|
||||
);
|
||||
}
|
||||
161
app/components/pipeline/TablaPipe.js
Normal file
161
app/components/pipeline/TablaPipe.js
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
import PrioridadBadge from "./PrioridadBadge";
|
||||
import { DYN, ACT_COLOR, money, money2 } from "../../lib/constants";
|
||||
import AgendarBoton from "../actividades/AgendarBoton";
|
||||
|
||||
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>
|
||||
<AgendarBoton opp={{ id: o.id, name: o.name, cliente: o.cliente, ownerId: o.ownerId, forecast: o.forecast, tipoCodigo: o.tipoCodigo }} />
|
||||
</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>
|
||||
);
|
||||
}
|
||||
88
app/components/pipeline/TablaPrevision.js
Normal file
88
app/components/pipeline/TablaPrevision.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import PrioridadBadge from "./PrioridadBadge";
|
||||
import { DYN, ACT_COLOR, money } from "../../lib/constants";
|
||||
import AgendarBoton from "../actividades/AgendarBoton";
|
||||
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>
|
||||
<AgendarBoton opp={{ id: o.id, name: o.name, cliente: o.cliente, ownerId: o.ownerId, forecast: o.forecast, tipoCodigo: o.tipoCodigo }} />
|
||||
</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>
|
||||
);
|
||||
}
|
||||
27
app/components/plan/AccionesFila.js
Normal file
27
app/components/plan/AccionesFila.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"use client";
|
||||
import Link from "next/link";
|
||||
import GestionarActividad from "../actividades/GestionarActividad";
|
||||
import AgendarBoton from "../actividades/AgendarBoton";
|
||||
import { localDeIso } from "../../lib/agendador";
|
||||
|
||||
const ICONO = { Llamada: "📞", Cita: "🤝", Tarea: "☑" };
|
||||
const hhmm = (m) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
|
||||
// Instante con que se muestra la actividad: llamadas y visitas, su inicio; la tarea, su vencimiento.
|
||||
const instante = (a) => (a.tipo === "Tarea" ? a.scheduledend || a.scheduledstart : a.scheduledstart || a.scheduledend);
|
||||
|
||||
// Acciones de una fila del plan: gestionar (completar, reprogramar, cancelar) cada actividad abierta y agendar otra,
|
||||
// sin salir a Dynamics. En filas de cuenta, enlace a su ficha. No se imprime.
|
||||
export default function AccionesFila({ acts, opp }) {
|
||||
const abiertas = (acts || []).filter((a) => a.estado === "abierta");
|
||||
return (
|
||||
<span className="plan-acciones">
|
||||
{abiertas.map((a) => (
|
||||
<GestionarActividad key={a.id} a={a} className="plan-gst" title={`Gestionar: ${a.asunto || a.tipo}`}>
|
||||
{ICONO[a.tipo]} {instante(a) ? hhmm(localDeIso(instante(a)).min) : a.tipo}
|
||||
</GestionarActividad>
|
||||
))}
|
||||
{opp.etn === "opportunity" && <AgendarBoton opp={opp} />}
|
||||
{opp.etn === "account" && <Link className="plan-agendar" href={`/cuentas/${opp.id}`}>Ficha</Link>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
198
app/components/plan/AgendaCronologica.js
Normal file
198
app/components/plan/AgendaCronologica.js
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
"use client";
|
||||
import { Fragment, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import GestionarActividad from "../actividades/GestionarActividad";
|
||||
import AgendarBoton from "../actividades/AgendarBoton";
|
||||
import { money, registroUrl } from "../../lib/constants";
|
||||
import { minAHora } from "../../lib/agendador";
|
||||
import { SECCIONES } from "../../lib/plan";
|
||||
import { ICONO_TIPO, ROTULO_TIPO, agrupar, intercalar, totales, etiquetaDia, durTxt } from "../../lib/agendaDia";
|
||||
import { txtActividades } from "../../lib/planDia";
|
||||
|
||||
// Vista cronológica (solo pantalla) del Plan del Día y del Plan de Actividades: UNA tabla, una fila por actividad,
|
||||
// ordenada por hora. El objetivo es una marca de color y un chip que filtra (en el cliente). El PDF NO usa este componente:
|
||||
// se sigue imprimiendo por objetivo con PlanSeccionDia / PlanSeccionPeriodo.
|
||||
// - `items`: lista plana (lib/agendaDia.listaPlana), ya con cruces y ya filtrada por ?gc=1 / ?venc=1.
|
||||
// - `agruparPor`: "owner" (gerente en Plan del Día), "dia" (Plan de Actividades) o null (un solo ejecutivo y día).
|
||||
// - `huecos`: huecos libres (solo Plan del Día de un ejecutivo); `ahora`: { dia, min } si hay que dibujar la línea «Ahora».
|
||||
export default function AgendaCronologica({ items, agruparPor = null, colEjecutivo = false, modo = "dia", huecos = [], ahora = null, hoy, hrefAgendar = null }) {
|
||||
const [filtro, setFiltro] = useState("todas"); // "todas" | clave de sección | "gv"
|
||||
const [plegados, setPlegados] = useState({});
|
||||
|
||||
const visibles = useMemo(
|
||||
() => items.filter((it) => (filtro === "todas" ? true : filtro === "gv" ? it.esGC : it.sec === filtro)),
|
||||
[items, filtro]
|
||||
);
|
||||
const grupos = useMemo(() => (agruparPor ? agrupar(visibles, agruparPor) : [{ key: "todo", items: visibles }]), [visibles, agruparPor]);
|
||||
const tot = useMemo(() => totales(visibles), [visibles]);
|
||||
|
||||
// Primera aparición de cada oportunidad en el orden de la tabla: las demás actividades de la misma oportunidad
|
||||
// muestran su MRR atenuado (no se suma de nuevo; el pie cuenta cada oportunidad una vez).
|
||||
const primero = useMemo(() => {
|
||||
const vistos = new Set();
|
||||
const p = new Set();
|
||||
for (const g of grupos) for (const it of g.items) if (!vistos.has(it.fila)) { vistos.add(it.fila); p.add(it.id); }
|
||||
return p;
|
||||
}, [grupos]);
|
||||
|
||||
const chips = useMemo(
|
||||
() => [
|
||||
{ k: "todas", etiqueta: "Todas", n: items.length },
|
||||
...SECCIONES.map((s) => {
|
||||
const its = items.filter((it) => it.sec === s.key);
|
||||
return { k: s.key, etiqueta: s.titulo, n: its.length, mrr: totales(its).mrr, sec: s.key };
|
||||
}),
|
||||
{ k: "gv", etiqueta: "👥 Con GV", n: items.filter((it) => it.esGC).length },
|
||||
],
|
||||
[items]
|
||||
);
|
||||
|
||||
const nCols = 6 + (colEjecutivo ? 1 : 0);
|
||||
const nombreGrupo = (g) => (agruparPor === "dia" ? `${etiquetaDia(g.key)}${g.key === hoy ? " · hoy" : ""}` : g.key);
|
||||
|
||||
function filasDeGrupo(g) {
|
||||
const dia = g.items[0]?.dia ?? (agruparPor === "dia" ? g.key : null);
|
||||
const ahoraMin = ahora && dia === ahora.dia ? ahora.min : null;
|
||||
const hs = filtro === "todas" ? huecos.filter((h) => h.dia === dia) : [];
|
||||
return intercalar(g.items, { huecos: hs, ahoraMin, conSeparadorTareas: modo === "dia" });
|
||||
}
|
||||
|
||||
function filaActividad(it) {
|
||||
const cls = ["ag-fila", it.completada ? "ag-hecha" : "", it.vencida ? "ag-venc" : "", it.cruce ? "ag-solape" : ""].filter(Boolean).join(" ");
|
||||
const opp = { ...it.opp, ownerName: it.owner };
|
||||
const nombreOpp = it.opp.etn === "opportunity" && it.opp.nombre && it.opp.nombre !== it.opp.cliente ? it.opp.nombre : null;
|
||||
return (
|
||||
<tr key={it.id} className={cls} data-sec={it.sec}>
|
||||
<td className="c-hora">
|
||||
<span className="ag-h">{it.completada && <span className="plan-check" title="Completada">✓ </span>}{it.min == null ? "—" : minAHora(it.min)}</span>
|
||||
<small>{durTxt(it)}</small>
|
||||
</td>
|
||||
<td className="c-tipo">{ICONO_TIPO[it.tipo]} {ROTULO_TIPO[it.tipo] || it.tipo}</td>
|
||||
<td className="c-cli">
|
||||
<a className="opp" href={registroUrl(it.opp.etn, it.opp.id)} target="_blank" rel="noopener">{it.opp.cliente || it.opp.nombre || "—"}</a>
|
||||
{it.opp.etn === "incident" && <span className="plan-ref"> (caso)</span>}
|
||||
{it.opp.etn === "account" && <span className="plan-ref"> (cuenta)</span>}
|
||||
{it.gv.map((g) => <span key={g.k} className={`gv-tag ${g.k}`}>{g.txt}</span>)}
|
||||
{it.vencida && <span className="ag-vtag">VENCIDA</span>}
|
||||
{nombreOpp && <span className="ag-opp">{nombreOpp}</span>}
|
||||
{it.cruce && <span className="ag-cruce">⚠ se cruza con la {it.cruce}</span>}
|
||||
</td>
|
||||
{colEjecutivo && <td className="c-eje">{it.owner}</td>}
|
||||
<td className="c-obj"><span className={`ag-obj ag-sc-${it.sec}`}><i />{it.objetivo}</span></td>
|
||||
<td className={`num c-mrr${primero.has(it.id) ? "" : " ag-rep"}`} title={primero.has(it.id) ? undefined : "Misma oportunidad que otra fila: no se suma de nuevo en el total"}>
|
||||
{it.valor == null ? "—" : money(it.valor)}
|
||||
</td>
|
||||
<td className="c-acc">
|
||||
<span className="plan-acciones">
|
||||
{!it.completada && (
|
||||
<GestionarActividad a={it.a} className="plan-gst" title={`Gestionar: ${it.a.asunto || it.tipo}`}>Gestionar</GestionarActividad>
|
||||
)}
|
||||
{it.opp.etn === "opportunity" && <AgendarBoton opp={opp} />}
|
||||
{it.opp.etn === "account" && <Link className="plan-agendar" href={`/cuentas/${it.opp.id}`}>Ficha</Link>}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function renderFila(f, i, g) {
|
||||
if (f.k === "act") return filaActividad(f.it);
|
||||
if (f.k === "ahora")
|
||||
return (
|
||||
<tr key={`ahora-${g.key}-${i}`} className="ag-ahora"><td colSpan={nCols}><div className="ag-linea-ahora">AHORA {minAHora(f.min)}</div></td></tr>
|
||||
);
|
||||
if (f.k === "hueco") {
|
||||
const { h } = f;
|
||||
return (
|
||||
<tr key={`hueco-${g.key}-${h.desde}`} className="ag-hueco">
|
||||
<td colSpan={nCols}>
|
||||
Libre {minAHora(h.desde)} – {minAHora(h.hasta)} · cabe {h.visitas} {h.visitas === 1 ? "visita" : "visitas"} o hasta {h.llamadas} llamadas
|
||||
{hrefAgendar && <> · <Link href={hrefAgendar}>Agendar ▸</Link></>}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
return <tr key={`tareas-${g.key}-${i}`} className="ag-grupo-tareas"><td colSpan={nCols}>Tareas del día · sin hora fija</td></tr>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ag-crono no-print">
|
||||
<div className="ag-chips" role="group" aria-label="Filtrar por objetivo">
|
||||
{chips.map((c) => (
|
||||
<button
|
||||
key={c.k}
|
||||
type="button"
|
||||
className={`ag-chip${c.sec ? ` ag-sc-${c.sec}` : ""}${filtro === c.k ? " on" : ""}`}
|
||||
aria-pressed={filtro === c.k}
|
||||
onClick={() => setFiltro(c.k)}
|
||||
>
|
||||
{c.sec && <i />}
|
||||
{c.etiqueta} <small>{c.n}{c.mrr != null && c.n > 0 ? ` · ${money(c.mrr)}` : ""}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="ts">
|
||||
<table className="ag-tbl">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="c-hora">Hora</th>
|
||||
<th className="c-tipo">Actividad</th>
|
||||
<th className="c-cli">Cliente / oportunidad</th>
|
||||
{colEjecutivo && <th className="c-eje">Ejecutivo</th>}
|
||||
<th className="c-obj">Objetivo</th>
|
||||
<th className="num c-mrr">MRR</th>
|
||||
<th className="c-acc">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{grupos.map((g) => {
|
||||
const cerrado = agruparPor && plegados[g.key];
|
||||
const t = totales(g.items);
|
||||
const filas = cerrado ? [] : filasDeGrupo(g);
|
||||
return (
|
||||
<Fragment key={g.key}>
|
||||
{agruparPor && (
|
||||
<tr key={`g-${g.key}`} className="ag-grupo">
|
||||
<td colSpan={nCols}>
|
||||
<button type="button" aria-expanded={!cerrado} onClick={() => setPlegados((p) => ({ ...p, [g.key]: !p[g.key] }))}>
|
||||
<span aria-hidden="true">{cerrado ? "▸" : "▾"}</span> {nombreGrupo(g)} · {txtActividades(t.n)} · {money(t.mrr)}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{filas.map((f, i) => renderFila(f, i, g))}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{!visibles.length && (
|
||||
<tr className="ag-vacio"><td colSpan={nCols}>{filtro === "todas" ? "Sin actividades agendadas." : "Sin actividades con este filtro."}</td></tr>
|
||||
)}
|
||||
{!visibles.length && filtro === "todas" && huecos.map((h) => (
|
||||
<tr key={`hv-${h.dia}-${h.desde}`} className="ag-hueco">
|
||||
<td colSpan={nCols}>
|
||||
Libre {minAHora(h.desde)} – {minAHora(h.hasta)} · cabe {h.visitas} {h.visitas === 1 ? "visita" : "visitas"} o hasta {h.llamadas} llamadas
|
||||
{hrefAgendar && <> · <Link href={hrefAgendar}>Agendar ▸</Link></>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan={nCols - 2} className="num">
|
||||
<strong>{modo === "dia" ? "Total del día" : "Total del período"} · {txtActividades(tot.n)}</strong>
|
||||
</td>
|
||||
<td className="num c-mrr"><strong>{money(tot.mrr)}</strong></td>
|
||||
<td />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<p className="ag-leyenda">
|
||||
✓ atenuada = completada · hora en rojo = vencida · barra amarilla = se cruza con otra · MRR atenuado = misma oportunidad que otra fila (se cuenta una vez en el total)
|
||||
{agruparPor === "dia" ? " · el MRR de cada día cuenta cada oportunidad una vez ese día" : ""}
|
||||
{huecos.length ? " · franja rayada = hueco libre de 60 min o más" : ""}.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
566
app/components/plan/AgendadorPanel.js
Normal file
566
app/components/plan/AgendadorPanel.js
Normal file
|
|
@ -0,0 +1,566 @@
|
|||
"use client";
|
||||
|
||||
import { Fragment, useEffect, 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, NIVELES_PRIO, proponer, validar, horasDe, minAHora, sumarFijos, baseItem, textoHorario,
|
||||
ventanaDe, fechaMaxima, calcularPrioridades,
|
||||
} from "../../lib/agendador";
|
||||
import { crearLoteAction, deshacerLoteAction } from "../../agendador/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));
|
||||
const fechaLarga = (iso) => { const [y, m, d] = iso.split("-"); return `${d}/${m}/${y.slice(2)}`; };
|
||||
const fechaCorta = (iso) => iso.split("-").reverse().slice(0, 2).join("/");
|
||||
const sinAcentos = (t) => String(t || "").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||
const pctDe = (s) => parseInt(s, 10) || 0;
|
||||
|
||||
// Filtros para afinar qué oportunidades se quieren agendar. Dentro de un filtro, las opciones suman
|
||||
// (o); entre filtros se combinan (y). Vacío = todas. NINGÚN filtro de menú viene activado de entrada (el ejecutivo ve
|
||||
// todas sus oportunidades abiertas, 2026-11-06); desde 2026-11-11 sí viene activado «Ocultar las que ya tienen actividad».
|
||||
// `visible`: a la vista en la franja; el resto queda bajo «Más filtros».
|
||||
// «Cierre estimado» se mide contra los días de agendado (ventana).
|
||||
const ORDEN_CIERRE = ["Vencida (antes de esos días)", "En esos días", "Resto del mes", "Mes siguiente", "Más adelante", "Sin fecha"];
|
||||
const finDeMes = (iso, sumar = 0) => {
|
||||
const [y, m] = iso.split("-").map(Number);
|
||||
return new Date(Date.UTC(y, m + sumar, 0)).toISOString().slice(0, 10);
|
||||
};
|
||||
function bucketCierre(c, v) {
|
||||
const d = c.cierre;
|
||||
if (!d) return ORDEN_CIERRE[5];
|
||||
if (d < v.desde) return ORDEN_CIERRE[0];
|
||||
if (d <= v.hasta) return ORDEN_CIERRE[1];
|
||||
if (d <= finDeMes(v.desde)) return ORDEN_CIERRE[2];
|
||||
if (d <= finDeMes(v.desde, 1)) return ORDEN_CIERRE[3];
|
||||
return ORDEN_CIERRE[4];
|
||||
}
|
||||
const FILTROS = [
|
||||
{ k: "tipo", lbl: "Tipo de oportunidad", visible: true, valor: (c) => c.tipo || "(sin tipo)" },
|
||||
{ k: "prio", lbl: "Prioridad", visible: true, valor: (c) => c.prioNivel, orden: NIVELES_PRIO },
|
||||
{ k: "plan", lbl: "Plan de cierre", valor: (c) => c.plan || "Sin plan de cierre" },
|
||||
{ k: "forecast", lbl: "Categoría de previsión", valor: (c) => c.forecast || "Sin categoría" },
|
||||
{ k: "cierre", lbl: "Cierre", visible: true, valor: (c, v) => bucketCierre(c, v), orden: ORDEN_CIERRE },
|
||||
];
|
||||
const SIN_FILTROS = { prio: [], tipo: [], plan: [], forecast: [], cierre: [] };
|
||||
const pasa = (c, filtros, v, salvo) => FILTROS.every((f) => f.k === salvo || !filtros[f.k].length || filtros[f.k].includes(f.valor(c, v)));
|
||||
|
||||
// Orden de la tabla. Por defecto, VALOR de mayor a menor (2026-11-06); los encabezados con ▲▼ cambian el orden.
|
||||
const ORDENES = {
|
||||
valor: (x, y) => (y.valor || 0) - (x.valor || 0),
|
||||
prio: (x, y) => (x.prioRank ?? 9) - (y.prioRank ?? 9) || (y.valor || 0) - (x.valor || 0),
|
||||
cliente: (x, y) => String(x.cliente || x.nombre || "").localeCompare(String(y.cliente || y.nombre || ""), "es"),
|
||||
cierre: (x, y) => (x.cierre || "9999-12-31").localeCompare(y.cierre || "9999-12-31"),
|
||||
forecast: (x, y) => (y.pct || 0) - (x.pct || 0),
|
||||
};
|
||||
const ORDEN_INICIAL = { k: "valor", dir: 1 };
|
||||
|
||||
// Agendador de actividades (PILOTO). Página propia: trae TODAS las oportunidades abiertas del ejecutivo;
|
||||
// se elige desde qué fecha agendar (hasta 30 días) y se reparte en 5 días hábiles a partir de ahí. La
|
||||
// persona marca las que va a agendar y ajusta día/hora/tipo/objetivo; lo marcado o editado a mano queda
|
||||
// FIJO y el resto se acomoda alrededor. «Crear en Dynamics» las crea con el propietario de la
|
||||
// oportunidad; nada se escribe antes. Diseño: agendador-automatico-diseno.md.
|
||||
export default function AgendadorPanel({ fechaInicial, ownerEmail, ownerName, hoy, ahoraMin, candidatos, actPorOpp, existentes, bloques, lotes }) {
|
||||
const router = useRouter();
|
||||
const [pendiente, empezar] = useTransition();
|
||||
const maxFecha = fechaMaxima(hoy);
|
||||
const [fecha, setFecha] = useState(fechaInicial || hoy);
|
||||
const dias = useMemo(() => ventanaDe(fecha, hoy), [fecha, hoy]);
|
||||
const ventana = useMemo(() => ({ desde: dias[0] || hoy, hasta: dias[dias.length - 1] || hoy }), [dias, hoy]);
|
||||
const base = { dias, existentes, bloques, hoy, ahoraMin };
|
||||
const [tipoTodas, setTipoTodas] = useState("Llamada");
|
||||
const [filtros, setFiltros] = useState(SIN_FILTROS);
|
||||
const [busqueda, setBusqueda] = useState("");
|
||||
const [ocultarConAct, setOcultarConAct] = useState(true);
|
||||
const [masFiltros, setMasFiltros] = useState(false);
|
||||
const [orden, setOrden] = useState(ORDEN_INICIAL);
|
||||
const [abierto, setAbierto] = useState(null); // filtro con el menú desplegado
|
||||
// Lo que la persona decidió a mano, por oportunidad: { tipo, dia, hora, objetivo, incluir, tocada }.
|
||||
const [edits, setEdits] = useState({});
|
||||
const [creadas, setCreadas] = useState([]); // filas ya creadas en esta sesión (con su creada)
|
||||
const [resultado, setResultado] = useState(null);
|
||||
const [aviso, setAviso] = useState(null);
|
||||
|
||||
// Cierra el menú al hacer clic fuera o con Escape.
|
||||
useEffect(() => {
|
||||
if (!abierto) return;
|
||||
const fuera = (e) => { if (!(e.target instanceof Element) || !e.target.closest(".agd-filtro")) setAbierto(null); };
|
||||
const tecla = (e) => { if (e.key === "Escape") setAbierto(null); };
|
||||
document.addEventListener("mousedown", fuera);
|
||||
document.addEventListener("keydown", tecla);
|
||||
return () => { document.removeEventListener("mousedown", fuera); document.removeEventListener("keydown", tecla); };
|
||||
}, [abierto]);
|
||||
|
||||
// Prioridad sugerida de cada oportunidad (sobre la cartera completa del ejecutivo).
|
||||
const conPrio = useMemo(() => {
|
||||
const m = calcularPrioridades(candidatos, hoy);
|
||||
return candidatos.map((c) => ({ ...c, ...m.get(c.id) }));
|
||||
}, [candidatos, hoy]);
|
||||
|
||||
// ¿Ya tiene una actividad agendada (no cancelada) en los días que se planifican?
|
||||
const conActividad = (c) => (actPorOpp[c.id] || []).some((d) => d >= ventana.desde && d <= ventana.hasta);
|
||||
const fechaActividad = (c) => (actPorOpp[c.id] || []).filter((d) => d >= ventana.desde && d <= ventana.hasta).sort()[0];
|
||||
|
||||
const idsCreadas = useMemo(() => new Set(creadas.map((c) => c.oppId)), [creadas]);
|
||||
const disponibles = useMemo(() => conPrio.filter((c) => !idsCreadas.has(c.id)), [conPrio, idsCreadas]);
|
||||
const q = sinAcentos(busqueda.trim());
|
||||
// Lo que pasa búsqueda y «ocultar» (antes de los filtros de menú).
|
||||
const baseVisible = useMemo(
|
||||
() => disponibles.filter((c) => (!q || sinAcentos(`${c.cliente || ""} ${c.nombre || ""}`).includes(q)) && !(ocultarConAct && conActividad(c))),
|
||||
[disponibles, q, ocultarConAct, ventana, actPorOpp] // eslint-disable-line react-hooks/exhaustive-deps
|
||||
);
|
||||
const coinciden = useMemo(() => baseVisible.filter((c) => pasa(c, filtros, ventana)), [baseVisible, filtros, ventana]);
|
||||
const marcadasIds = Object.keys(edits).filter((k) => edits[k].incluir);
|
||||
|
||||
// Opciones de cada filtro con su conteo FRENTE A LOS OTROS filtros (las que quedarían en 0 se ven en gris).
|
||||
const opciones = useMemo(() => {
|
||||
const out = {};
|
||||
for (const f of FILTROS) {
|
||||
const total = new Map();
|
||||
conPrio.forEach((c) => total.set(f.valor(c, ventana), (total.get(f.valor(c, ventana)) || 0) + 1));
|
||||
const visibles = new Map();
|
||||
baseVisible.filter((c) => pasa(c, filtros, ventana, f.k)).forEach((c) => visibles.set(f.valor(c, ventana), (visibles.get(f.valor(c, ventana)) || 0) + 1));
|
||||
out[f.k] = [...total.entries()]
|
||||
.sort((a, b) =>
|
||||
f.orden ? f.orden.indexOf(a[0]) - f.orden.indexOf(b[0])
|
||||
: (f.k === "forecast" ? pctDe(b[0]) - pctDe(a[0]) : 0) || b[1] - a[1] || a[0].localeCompare(b[0], "es"))
|
||||
.map(([v]) => [v, visibles.get(v) || 0]);
|
||||
}
|
||||
return out;
|
||||
}, [conPrio, baseVisible, filtros, ventana]);
|
||||
|
||||
// Filas visibles = las que coinciden + las marcadas que el filtro/búsqueda dejó fuera.
|
||||
const filas = useMemo(() => {
|
||||
const porId = new Map(conPrio.map((c) => [c.id, c]));
|
||||
const marcadasFuera = marcadasIds.filter((id) => porId.has(id) && !coinciden.some((c) => c.id === id)).map((id) => porId.get(id));
|
||||
const visibles = [...coinciden, ...marcadasFuera];
|
||||
// Filas sin decisión a mano: se acomodan alrededor de las marcadas (que quedan fijas). Las que ya
|
||||
// tienen actividad en esos días no se proponen.
|
||||
const fijas = marcadasIds.map((id) => ({ ...edits[id] }));
|
||||
const { existentes: ex, bloques: bl } = sumarFijos(existentes, bloques, fijas);
|
||||
const auto = proponer({ candidatos: visibles.filter((c) => !edits[c.id] && !conActividad(c)), ...base, existentes: ex, bloques: bl, tipo: tipoTodas });
|
||||
const autoPorId = new Map(auto.map((i) => [i.oppId, { ...i, incluir: false }]));
|
||||
const filasV = visibles.map((c) => {
|
||||
const e = edits[c.id];
|
||||
if (!e) {
|
||||
if (conActividad(c)) return { ...baseItem(c, tipoTodas), dia: null, hora: null, sinCupo: false, incluir: false, conActividad: fechaActividad(c) };
|
||||
return autoPorId.get(c.id);
|
||||
}
|
||||
return { ...baseItem(c, e.tipo), tipo: e.tipo, dia: e.dia, hora: e.hora, objetivo: e.objetivo, gv: !!e.gv && e.tipo !== "Tarea", incluir: !!e.incluir, sinCupo: !e.dia, tocada: !!e.tocada, fueraDelFiltro: !coinciden.some((x) => x.id === c.id) };
|
||||
});
|
||||
const cmp = ORDENES[orden.k];
|
||||
return filasV.sort((x, y) => orden.dir * cmp(x, y) || ORDENES.valor(x, y));
|
||||
}, [conPrio, coinciden, edits, tipoTodas, dias, existentes, bloques, hoy, ahoraMin, orden, actPorOpp]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const marcadas = filas.filter((f) => f.incluir);
|
||||
const val = useMemo(() => validar({ items: marcadas, ...base }), [filas, dias, existentes, bloques, hoy, ahoraMin]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const congelar = (f, extra = {}) => ({ tipo: f.tipo, dia: f.dia, hora: f.hora, objetivo: f.objetivo, gv: !!f.gv, incluir: !!f.incluir, tocada: !!f.tocada, ...extra });
|
||||
const editar = (f, cambios) => setEdits((p) => ({ ...p, [f.key]: congelar(f, { ...cambios, tocada: true }) }));
|
||||
const marcar = (f, valor) =>
|
||||
setEdits((p) => {
|
||||
const n = { ...p };
|
||||
if (valor) n[f.key] = congelar(f, { incluir: true });
|
||||
else if (f.tocada) n[f.key] = congelar(f, { incluir: false });
|
||||
else delete n[f.key];
|
||||
return n;
|
||||
});
|
||||
const marcarTodas = (valor) =>
|
||||
setEdits((p) => {
|
||||
const n = { ...p };
|
||||
filas.forEach((f) => {
|
||||
if (valor) { if (f.dia && !f.conActividad) n[f.key] = congelar(f, { incluir: true }); }
|
||||
else if (f.incluir) { if (f.tocada) n[f.key] = congelar(f, { incluir: false }); else delete n[f.key]; }
|
||||
});
|
||||
return n;
|
||||
});
|
||||
// «Marcar GV en las seleccionadas»: solo llamadas y visitas (las tareas no llevan GV).
|
||||
const marcarGV = () =>
|
||||
setEdits((p) => Object.fromEntries(Object.entries(p).map(([k, e]) => [k, e.incluir && e.tipo !== "Tarea" ? { ...e, gv: true } : e])));
|
||||
const restablecer = () => setEdits((p) => Object.fromEntries(Object.entries(p).filter(([, e]) => e.incluir)));
|
||||
|
||||
const cambiarTipo = (f, tipo) => {
|
||||
const horas = horasDe(tipo).map(minAHora);
|
||||
const hora = tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : horas.includes(f.hora) ? f.hora : horas[0];
|
||||
editar(f, { tipo, hora: f.dia ? hora : null, gv: tipo === "Tarea" ? false : f.gv });
|
||||
};
|
||||
const cambiarDia = (f, dia) => {
|
||||
const horas = horasDe(f.tipo).map(minAHora);
|
||||
const hora = f.tipo === "Tarea" ? minAHora(AGENDADOR.horaTarea) : f.hora && horas.includes(f.hora) ? f.hora : horas[0] || "";
|
||||
editar(f, { dia: dia || null, hora: dia ? hora : null });
|
||||
};
|
||||
|
||||
// Cambiar la fecha cambia los días de agendado: lo marcado se descarta (sus días ya no valdrían).
|
||||
const cambiarFecha = (nueva) => {
|
||||
if (!nueva) return;
|
||||
const f = nueva < hoy ? hoy : nueva > maxFecha ? maxFecha : nueva;
|
||||
if (f === fecha) return;
|
||||
if (marcadasIds.length && !window.confirm("Al cambiar la fecha se desmarcan las oportunidades que habías marcado. ¿Continuar?")) return;
|
||||
setEdits({});
|
||||
setFecha(f);
|
||||
};
|
||||
|
||||
const ordenarPor = (k) => setOrden((o) => (o.k === k ? { k, dir: -o.dir } : { k, dir: k === "valor" || k === "forecast" ? 1 : 1 }));
|
||||
const flecha = (k) => (orden.k === k ? (orden.dir === 1 ? " ▼" : " ▲") : "");
|
||||
|
||||
const crear = () => {
|
||||
setAviso(null);
|
||||
if (!marcadas.length || !val.ok) return;
|
||||
const resumen = TIPOS_AGENDADOR.map((t) => [t, marcadas.filter((i) => i.tipo === t).length]).filter(([, n]) => n).map(([t, n]) => `${n} ${NOMBRE_PLURAL[t]}`).join(", ");
|
||||
const nGV = marcadas.filter((i) => i.gv).length;
|
||||
const textoGV = nGV ? ` ${nGV} llevan a Gerencia Comercial (GV): se marca su participación en la oportunidad${marcadas.some((i) => i.gv && i.tipo === "Cita") ? " y las visitas se envían como invitación a Marco" : ""}.` : "";
|
||||
if (!window.confirm(`Se crearán en Dynamics ${marcadas.length} actividades (${resumen}) para ${ownerName}, a su nombre.${textoGV} ¿Continuar?`)) return;
|
||||
const enviadas = marcadas;
|
||||
empezar(async () => {
|
||||
const r = await crearLoteAction({
|
||||
ownerEmail,
|
||||
fecha,
|
||||
items: enviadas.map((i) => ({ oppId: i.oppId, nombre: i.nombre, cliente: i.cliente, tipo: i.tipo, objetivo: i.objetivo, dia: i.dia, hora: i.hora, gv: !!i.gv })),
|
||||
});
|
||||
if (!r.ok) { setAviso({ mal: true, texto: r.error }); return; }
|
||||
const hechas = new Map(r.resultados.filter((x) => x.estado === "creada").map((x) => [x.oppId, x]));
|
||||
setCreadas((p) => [...enviadas.filter((f) => hechas.has(f.oppId)).map((f) => ({ ...f, incluir: false, creada: hechas.get(f.oppId) })), ...p]);
|
||||
setEdits((p) => Object.fromEntries(Object.entries(p).filter(([id]) => !hechas.has(id))));
|
||||
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.oppRestauradas ? `, ${r.oppRestauradas} oportunidad(es) sin la marca de GV que puso la tanda` : ""}${r.errores ? `, ${r.errores} con error` : ""}.` } : { mal: true, texto: r.error });
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
const hayFiltros = FILTROS.some((f) => filtros[f.k].length);
|
||||
const hayCitas = marcadas.some((i) => i.tipo === "Cita");
|
||||
const nGV = marcadas.filter((i) => i.gv).length;
|
||||
const sinCupo = filas.filter((i) => i.sinCupo && !i.dia).length;
|
||||
const fueraDeFiltro = filas.filter((f) => f.fueraDelFiltro).length;
|
||||
const filasTabla = [...creadas, ...filas];
|
||||
const nMalos = marcadas.filter((i) => (val.porItem[i.key] || []).length).length;
|
||||
const nExtra = FILTROS.filter((f) => !f.visible).reduce((n, f) => n + filtros[f.k].length, 0);
|
||||
const quitarTodo = () => { setFiltros(SIN_FILTROS); setBusqueda(""); setOcultarConAct(false); };
|
||||
const nTipo = (t) => marcadas.filter((i) => i.tipo === t).length;
|
||||
|
||||
// Un menú de filtro (botón + lista de opciones con casillas).
|
||||
const menuFiltro = (f) => {
|
||||
const sel = filtros[f.k];
|
||||
const resumen = sel.length === 0 ? "Todos" : sel.length === 1 ? sel[0] : `${sel.length} seleccionados`;
|
||||
return (
|
||||
<div key={f.k} className={`agd-filtro${abierto === f.k ? " abierto" : ""}`}>
|
||||
<button type="button" className="agd-filtro-b agd-filtro-c" aria-expanded={abierto === f.k} onClick={() => setAbierto(abierto === f.k ? null : f.k)}>
|
||||
<span className="agd-filtro-l">{f.lbl}:</span> <b>{resumen}</b>
|
||||
</button>
|
||||
{abierto === f.k && (
|
||||
<div className="agd-opts" role="menu">
|
||||
{opciones[f.k].map(([v, n]) => {
|
||||
const activo = sel.includes(v);
|
||||
return (
|
||||
<label key={v} className={n === 0 && !activo ? "agd-opt-0" : ""}>
|
||||
<input type="checkbox" checked={activo} onChange={() => setFiltros((p) => ({ ...p, [f.k]: activo ? sel.filter((x) => x !== v) : [...sel, v] }))} /> {v} <span className="agd-n">({n})</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
{sel.length > 0 && <button type="button" className="agd-btn-sec" onClick={() => setFiltros((p) => ({ ...p, [f.k]: [] }))}>Quitar este filtro</button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Aviso en línea bajo la fila: solo si hay algo que decir.
|
||||
const avisoDe = (it, probs) => {
|
||||
if (it.creada) {
|
||||
return (
|
||||
<span className="agd-ok">
|
||||
✓ Creada{it.creada.gv ? " con GV" : ""} ·{" "}
|
||||
<a href={actividadUrl({ tipo: it.creada.tipo, id: it.creada.activityId })} target="_blank" rel="noreferrer">abrir en CRM</a>
|
||||
{it.creada.avisoOpp ? <span className="agd-mal"> · {it.creada.avisoOpp}</span> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (it.conActividad) return { info: `Ya tiene una actividad agendada el ${fechaLarga(it.conActividad)}.` };
|
||||
if (it.sinCupo && !it.dia) return { info: "Sin cupo en esos días con estos máximos: elige un día a mano." };
|
||||
if (it.incluir && probs.length) return { mal: `⚠ ${probs.join(" ")}` };
|
||||
if (it.fueraDelFiltro) return { info: "Marcada; no coincide con el filtro actual." };
|
||||
if (it.incluir && it.gv) {
|
||||
return { info: it.tipo === "Cita" ? "Con GV: Marco recibe la invitación en su calendario y se marca «Participación de GV» en la oportunidad." : "Con GV: Gerencia Comercial queda como participante y se marca «Participación de GV» en la oportunidad." };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="plan-agd agd-pag no-print">
|
||||
<details className="agd-ayuda-d">
|
||||
<summary>
|
||||
<span className="agd-ayuda-i">ⓘ</span>
|
||||
<span><b>Elige la fecha → marca las oportunidades → «Crear».</b> Nada se crea hasta ese paso y queda a nombre del dueño de la oportunidad.</span>
|
||||
<span className="agd-ayuda-lk">¿Cómo funciona?</span>
|
||||
</summary>
|
||||
<div className="agd-ayuda">
|
||||
<ol>
|
||||
<li><b>Elige la fecha</b> desde la que quieres agendar (hasta 30 días) y, si quieres, <b>busca o filtra</b> las oportunidades.</li>
|
||||
<li><b>Marca</b> las que vas a agendar y ajusta el tipo, el día, la hora o el objetivo. Con «👥 Con GV» invitas a Gerencia Comercial.</li>
|
||||
<li>Pulsa <b>«Crear … en Dynamics»</b>. No se crea nada hasta ese paso, y las actividades quedan a nombre del propietario de la oportunidad.</li>
|
||||
</ol>
|
||||
<p>
|
||||
<b>Reglas:</b> de lunes a viernes, {textoHorario()}. Llamadas de {AGENDADOR.duracion.Llamada} min (horas cada {AGENDADOR.paso.Llamada} min) y visitas de {AGENDADOR.duracion.Cita} min (horas cada {AGENDADOR.paso.Cita} min).
|
||||
Máximo por día: {AGENDADOR.topes.Llamada} llamadas, {AGENDADOR.topes.Cita} visitas y {AGENDADOR.topes.Tarea} tareas (las tareas vencen a las {minAHora(AGENDADOR.horaTarea)}).
|
||||
Se muestran <b>todas las oportunidades abiertas</b> del ejecutivo, sin importar su fecha de cierre.
|
||||
</p>
|
||||
<p>
|
||||
<b>Qué se escribe en Dynamics:</b> las visitas salen con lugar «Oficina del cliente»; otros participantes se agregan en el CRM.
|
||||
Con «Con GV», la actividad lleva a Gerencia Comercial como participante y la oportunidad queda con «Participación de GV» (que suma a su puntuación); en las visitas, además, Marco recibe la invitación en su calendario de Outlook.
|
||||
Al «Deshacer» la tanda se cancelan las actividades abiertas y la oportunidad vuelve a su valor anterior.
|
||||
</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
{candidatos.length === 0 && creadas.length === 0 ? (
|
||||
<p className="agd-vacio">{ownerName} no tiene oportunidades abiertas con fecha de cierre estimada.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="agd-paso">
|
||||
<h4>1 · ¿Desde qué día agendas?</h4>
|
||||
<div className="agd-fecha">
|
||||
<input id="agd-fecha-i" type="date" value={fecha} min={hoy} max={maxFecha} onChange={(e) => cambiarFecha(e.target.value)} disabled={pendiente} aria-label="Agendar a partir del" />
|
||||
<span className="hint">Se reparte de <b>{dias.length ? `${diaCorto(dias[0])} a ${diaCorto(dias[dias.length - 1])}` : "—"}</b> · puedes elegir hasta el {fechaLarga(maxFecha)}</span>
|
||||
</div>
|
||||
<div className="agd-capg">
|
||||
{dias.map((d) => {
|
||||
const c = val.porDia[d] || { Llamada: 0, Cita: 0, Tarea: 0, ...(existentes[d] || {}) };
|
||||
return (
|
||||
<div key={d} className="agd-capd" title="Lo que ya tiene agendado ese día más lo que marcaste">
|
||||
<b className="agd-capd-t">{diaCorto(d)}</b>
|
||||
{TIPOS_AGENDADOR.map((t) => {
|
||||
const tope = AGENDADOR.topes[t];
|
||||
const n = c[t] || 0;
|
||||
return (
|
||||
<div key={t} className={`agd-cap${n >= tope ? " lleno" : ""}`}>
|
||||
<span className="agd-cap-k">{t === "Cita" ? "Visitas" : `${t}s`}</span>
|
||||
<span className="agd-cap-b"><i style={{ width: `${Math.min(100, Math.round((n / tope) * 100))}%` }} /></span>
|
||||
<span className="agd-cap-v">{n}/{tope}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="agd-paso">
|
||||
<h4>2 · ¿Qué oportunidades?</h4>
|
||||
<div className="agd-franja">
|
||||
<input
|
||||
type="search"
|
||||
className="agd-busca"
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
placeholder="🔍 Buscar cliente u oportunidad…"
|
||||
aria-label="Buscar cliente u oportunidad"
|
||||
/>
|
||||
{FILTROS.filter((f) => f.visible).map(menuFiltro)}
|
||||
<label className="agd-check">
|
||||
<input type="checkbox" checked={ocultarConAct} onChange={(e) => setOcultarConAct(e.target.checked)} /> Ocultar las que ya tienen actividad
|
||||
</label>
|
||||
<button type="button" className="agd-mas" aria-expanded={masFiltros} onClick={() => setMasFiltros((v) => !v)}>
|
||||
{masFiltros ? "- Menos filtros" : "+ Más filtros"}{!masFiltros && nExtra ? ` (${nExtra})` : ""}
|
||||
</button>
|
||||
</div>
|
||||
{masFiltros && <div className="agd-franja agd-franja-mas">{FILTROS.filter((f) => !f.visible).map(menuFiltro)}</div>}
|
||||
{hayFiltros && (
|
||||
<div className="agd-chips">
|
||||
{FILTROS.flatMap((f) => filtros[f.k].map((v) => (
|
||||
<button key={f.k + v} type="button" className="agd-chip" title={`Quitar «${v}»`} onClick={() => setFiltros((p) => ({ ...p, [f.k]: p[f.k].filter((x) => x !== v) }))}>
|
||||
{v} ✕
|
||||
</button>
|
||||
)))}
|
||||
<button type="button" className="agd-btn-sec" onClick={() => setFiltros(SIN_FILTROS)}>Limpiar filtros</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="agd-paso">
|
||||
<h4>3 · Marca y ajusta</h4>
|
||||
{coinciden.length === 0 && filas.length === 0 && creadas.length === 0 ? (
|
||||
<p className="agd-mal agd-grande">
|
||||
Ninguna oportunidad coincide con la búsqueda y los filtros.{" "}
|
||||
<button type="button" className="agd-btn-sec" onClick={quitarTodo}>Quitar filtros y búsqueda</button>
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="agd-acc">
|
||||
<button type="button" className="agd-btn-sec" onClick={() => marcarTodas(true)} disabled={pendiente || !filas.length}>Marcar todas ({filas.filter((f) => f.dia && !f.conActividad).length})</button>
|
||||
<button type="button" className="agd-btn-sec" onClick={() => marcarTodas(false)} disabled={pendiente || !marcadas.length}>Desmarcar</button>
|
||||
<button type="button" className="agd-btn-sec" onClick={restablecer} disabled={pendiente} title="Deshace tus cambios manuales en las filas no marcadas">Restablecer propuesta</button>
|
||||
<button type="button" className="agd-btn-sec" onClick={marcarGV} disabled={pendiente || !marcadas.some((m) => m.tipo !== "Tarea")} title="Pone «Con GV» en las llamadas y visitas marcadas">👥 Marcar GV en las seleccionadas</button>
|
||||
<label className="agd-tipo-todas">
|
||||
<span className="hint">Tipo para las no tocadas:</span>
|
||||
<select id="agd-tipo" value={tipoTodas} onChange={(e) => setTipoTodas(e.target.value)} disabled={pendiente} title="Aplica a las filas que no has tocado a mano">
|
||||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<span className="hint agd-acc-r">
|
||||
Mostrando {coinciden.length} de {disponibles.length} abiertas
|
||||
{(hayFiltros || q || ocultarConAct) && <> · <button type="button" className="agd-btn-sec" onClick={quitarTodo}>Quitar filtros y búsqueda</button></>}
|
||||
{fueraDeFiltro > 0 && ` · ${fueraDeFiltro} marcada${fueraDeFiltro === 1 ? "" : "s"} fuera del filtro (se conservan)`}
|
||||
{sinCupo > 0 && ` · ${sinCupo} sin cupo`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="agd-t7-w">
|
||||
<table className="agd-t7">
|
||||
<colgroup>
|
||||
<col style={{ width: "4%" }} />
|
||||
<col style={{ width: "28%" }} />
|
||||
<col style={{ width: "9%" }} />
|
||||
<col style={{ width: "14%" }} />
|
||||
<col style={{ width: "8%" }} />
|
||||
<col style={{ width: "25%" }} />
|
||||
<col style={{ width: "12%" }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th><button type="button" className="agd-th-b" onClick={() => ordenarPor("cliente")}>Cliente / oportunidad{flecha("cliente")}</button></th>
|
||||
<th><button type="button" className="agd-th-b" onClick={() => ordenarPor("prio")} title="Ordenar por prioridad sugerida">Prioridad{flecha("prio")}</button></th>
|
||||
<th>
|
||||
<button type="button" className="agd-th-b" onClick={() => ordenarPor("cierre")}>Cierre{flecha("cierre")}</button>
|
||||
{" · "}
|
||||
<button type="button" className="agd-th-b" onClick={() => ordenarPor("forecast")} title="Ordenar por categoría de previsión">Previsión{flecha("forecast")}</button>
|
||||
</th>
|
||||
<th className="num"><button type="button" className="agd-th-b" onClick={() => ordenarPor("valor")}>Valor{flecha("valor")}</button></th>
|
||||
<th>Propuesta</th>
|
||||
<th>Objetivo</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filasTabla.map((it) => {
|
||||
const hecha = !!it.creada;
|
||||
const bloqueada = !!it.conActividad;
|
||||
const probs = hecha ? [] : val.porItem[it.key] || [];
|
||||
const horas = horasDe(it.tipo).map(minAHora);
|
||||
const vencida = it.cierre && it.cierre < hoy;
|
||||
const av = avisoDe(it, probs);
|
||||
const apagada = hecha || bloqueada || pendiente;
|
||||
return (
|
||||
<Fragment key={it.key}>
|
||||
<tr className={`agd-f${hecha ? " agd-hecha" : it.incluir ? " agd-marcada" : bloqueada ? " agd-con-act" : ""}${av ? " agd-tiene-aviso" : ""}`}>
|
||||
<td>
|
||||
<input type="checkbox" checked={!!it.incluir && !hecha} disabled={apagada || (!it.dia && !it.incluir)} onChange={(e) => marcar(it, e.target.checked)} aria-label="Agendar esta oportunidad" title={bloqueada ? "Ya tiene una actividad agendada en esos días" : !it.dia && !it.incluir ? "Elige primero un día" : undefined} />
|
||||
</td>
|
||||
<td>
|
||||
<strong>{it.cliente || it.nombre}</strong>
|
||||
{it.cliente && <div className="agd-sub">{it.nombre}</div>}
|
||||
<div className="agd-sub">{it.tipoOpp || "—"} · {it.plan || "Sin plan de cierre"}</div>
|
||||
</td>
|
||||
<td>
|
||||
{it.prioNivel && (
|
||||
<span className={`agd-prio p-${NIVELES_PRIO.indexOf(it.prioNivel)}`} title={(it.prioMotivos || []).join(" · ") || undefined}>{it.prioNivel}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={vencida ? "agd-venc" : undefined}>
|
||||
{it.cierre ? fechaCorta(it.cierre) : "—"}
|
||||
{vencida && " · vencida"}
|
||||
<div className="agd-sub">{it.forecast || "Sin previsión"}</div>
|
||||
</td>
|
||||
<td className="num">{money(it.valor)}</td>
|
||||
<td>
|
||||
<div className="agd-prop">
|
||||
<select className="agd-s-tipo" aria-label="Tipo de actividad" value={it.tipo} disabled={apagada} onChange={(e) => cambiarTipo(it, e.target.value)}>
|
||||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||||
</select>
|
||||
<select className="agd-s-dia" aria-label="Día" value={it.dia || ""} disabled={apagada} onChange={(e) => cambiarDia(it, e.target.value)}>
|
||||
<option value="">— día —</option>
|
||||
{dias.map((d) => <option key={d} value={d}>{diaCorto(d)}</option>)}
|
||||
</select>
|
||||
{it.tipo === "Tarea" ? (
|
||||
<span className="agd-vence" title={`Las tareas vencen a las ${minAHora(AGENDADOR.horaTarea)}`}>vence {minAHora(AGENDADOR.horaTarea)}</span>
|
||||
) : (
|
||||
<select className="agd-s-hora" aria-label="Hora" value={it.hora || ""} disabled={apagada || !it.dia} onChange={(e) => editar(it, { hora: e.target.value })}>
|
||||
<option value="">—</option>
|
||||
{horas.map((h) => <option key={h} value={h}>{h}</option>)}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
{it.tipo !== "Tarea" && !hecha && !bloqueada && (
|
||||
<label className="agd-gv" title="Gerencia Comercial (Marco) participa en esta actividad">
|
||||
<input type="checkbox" checked={!!it.gv} disabled={pendiente} onChange={(e) => editar(it, { gv: e.target.checked })} /> 👥 Con GV
|
||||
</label>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<select aria-label="Objetivo" value={it.objetivo} disabled={apagada} onChange={(e) => editar(it, { objetivo: e.target.value })}>
|
||||
<option value="">— elegir —</option>
|
||||
{OBJETIVOS_AGENDADOR.map((o) => <option key={o} value={o}>{o}</option>)}
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
{av && (
|
||||
<tr className={`agd-aviso${av.mal ? " mal" : av.info ? " info" : " ok"}`}>
|
||||
<td colSpan={7}>{av.mal || av.info || av}</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{hayCitas && <p className="hint">Las visitas se crean con lugar «Oficina del cliente»; otros participantes e invitados se agregan en el CRM.</p>}
|
||||
|
||||
<div className="agd-pie-fijo">
|
||||
<span className="agd-pie-r">
|
||||
<b>{marcadas.length} actividad{marcadas.length === 1 ? "" : "es"}</b> · {nGV} con GV
|
||||
{marcadas.length > 0 && <> · {nTipo("Llamada")} llamada{nTipo("Llamada") === 1 ? "" : "s"} · {nTipo("Cita")} visita{nTipo("Cita") === 1 ? "" : "s"} · {nTipo("Tarea")} tarea{nTipo("Tarea") === 1 ? "" : "s"}</>}
|
||||
</span>
|
||||
{nMalos > 0 && <span className="agd-pie-mal">{nMalos} aviso{nMalos === 1 ? "" : "s"} por corregir</span>}
|
||||
{marcadas.length === 0 && <span className="agd-pie-sub">Marca al menos una oportunidad para poder crear.</span>}
|
||||
<button type="button" className="agd-pie-btn" disabled={pendiente || !marcadas.length || !val.ok} onClick={crear}>
|
||||
{pendiente ? "Trabajando…" : `Crear ${marcadas.length} actividad${marcadas.length === 1 ? "" : "es"} en Dynamics`}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{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.conGV ? ` (${resultado.conGV} con GV)` : ""}{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>
|
||||
))}
|
||||
{resultado.resultados.filter((x) => x.estado === "creada" && x.avisoOpp).map((x) => (
|
||||
<div key={x.oppId} className="agd-mal">{x.nombre || x.oppId}: {x.avisoOpp}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lotes.length > 0 && (
|
||||
<details className="agd-lotes">
|
||||
<summary>Tandas recientes ({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.items.some((x) => x.gv && x.estado === "creada") ? ` (${l.items.filter((x) => x.gv && x.estado === "creada").length} con GV)` : ""} · {fechaCorta(l.desde)} – {fechaCorta(l.hasta)}
|
||||
{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>
|
||||
);
|
||||
}
|
||||
94
app/components/plan/BarraSecciones.js
Normal file
94
app/components/plan/BarraSecciones.js
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"use client";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { money } from "../../lib/constants";
|
||||
|
||||
// Barra de secciones fija del Plan del Día: una casilla por sección (MRR, nombre y cantidad de actividades) + Total.
|
||||
// Clic = desplazamiento suave a la sección (ancla `sec-<key>`); la casilla de la sección visible se resalta.
|
||||
// En papel no sale la barra: la sustituye una línea de resumen («Cierre 1 · $350») solo en el PDF individual.
|
||||
// `casillas`: [{ key, titulo, mrr, acts }].
|
||||
export default function BarraSecciones({ casillas }) {
|
||||
const barra = useRef(null);
|
||||
const [activa, setActiva] = useState(null);
|
||||
const totalMrr = casillas.reduce((t, c) => t + c.mrr, 0);
|
||||
const totalActs = casillas.reduce((t, c) => t + c.acts, 0);
|
||||
|
||||
// Mide la cabecera fija de la app y la barra para que los títulos de sección no queden tapados al desplazarse.
|
||||
useEffect(() => {
|
||||
const raiz = document.documentElement;
|
||||
const medir = () => {
|
||||
const top = document.querySelector(".topbar")?.offsetHeight || 64;
|
||||
const alto = barra.current?.offsetHeight || 0;
|
||||
raiz.style.setProperty("--plan-top", `${top}px`);
|
||||
raiz.style.setProperty("--plan-offset", `${top + alto + 10}px`);
|
||||
};
|
||||
medir();
|
||||
window.addEventListener("resize", medir);
|
||||
return () => {
|
||||
window.removeEventListener("resize", medir);
|
||||
raiz.style.removeProperty("--plan-top");
|
||||
raiz.style.removeProperty("--plan-offset");
|
||||
};
|
||||
}, [casillas.length]);
|
||||
|
||||
// Resalta la sección visible: la primera (en orden) que cruza la franja bajo la barra.
|
||||
useEffect(() => {
|
||||
const visibles = new Set();
|
||||
const top = (document.querySelector(".topbar")?.offsetHeight || 64) + (barra.current?.offsetHeight || 0);
|
||||
const io = new IntersectionObserver(
|
||||
(entradas) => {
|
||||
entradas.forEach((e) => {
|
||||
const k = e.target.id.replace(/^sec-/, "");
|
||||
if (e.isIntersecting) visibles.add(k);
|
||||
else visibles.delete(k);
|
||||
});
|
||||
const primera = casillas.find((c) => visibles.has(c.key));
|
||||
if (primera) setActiva(primera.key);
|
||||
},
|
||||
{ rootMargin: `-${top}px 0px -55% 0px`, threshold: 0 }
|
||||
);
|
||||
casillas.forEach((c) => {
|
||||
const el = document.getElementById(`sec-${c.key}`);
|
||||
if (el) io.observe(el);
|
||||
});
|
||||
return () => io.disconnect();
|
||||
}, [casillas]);
|
||||
|
||||
function ir(key) {
|
||||
const el = document.getElementById(`sec-${key}`);
|
||||
if (!el) return;
|
||||
const reducido = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
||||
el.scrollIntoView({ behavior: reducido ? "auto" : "smooth", block: "start" });
|
||||
setActiva(key);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav ref={barra} className="plan-barra no-print" aria-label="Secciones del plan">
|
||||
{casillas.map((c) => (
|
||||
<button
|
||||
key={c.key}
|
||||
type="button"
|
||||
className={`plan-barra-i sec-${c.key}${activa === c.key ? " on" : ""}`}
|
||||
onClick={() => ir(c.key)}
|
||||
aria-current={activa === c.key ? "true" : undefined}
|
||||
>
|
||||
<span className="n">{money(c.mrr)}</span>
|
||||
<span className="l">{c.titulo} · {c.acts}</span>
|
||||
</button>
|
||||
))}
|
||||
<div className="plan-barra-i plan-barra-total" aria-label="Total">
|
||||
<span className="n">{money(totalMrr)}</span>
|
||||
<span className="l">Total · {totalActs}</span>
|
||||
</div>
|
||||
</nav>
|
||||
<div className="plan-obj-print" aria-hidden="true">
|
||||
{casillas.map((c) => (
|
||||
<span key={c.key} className={`plan-obj-i sec-${c.key}`}>
|
||||
<strong>{c.titulo}</strong> {c.acts} · {money(c.mrr)}
|
||||
</span>
|
||||
))}
|
||||
<span className="plan-obj-i plan-obj-total"><strong>Total</strong> {totalActs} · {money(totalMrr)}</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
88
app/components/plan/DetalleActividades.js
Normal file
88
app/components/plan/DetalleActividades.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
"use client";
|
||||
import { actividadUrl, money } from "../../lib/constants";
|
||||
import GestionarActividad from "../actividades/GestionarActividad";
|
||||
|
||||
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>
|
||||
<th></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>
|
||||
<td>
|
||||
{a.estadoFinal === "Completada" || a.estadoFinal === "Cancelada" ? null : (
|
||||
<GestionarActividad a={a} className="gst-act">Gestionar</GestionarActividad>
|
||||
)}
|
||||
</td>
|
||||
{!locked && <td>{a.owner}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
24
app/components/plan/GerenciaCelda.js
Normal file
24
app/components/plan/GerenciaCelda.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { gcDe, ETIQUETA_MODALIDAD } from "../../lib/gerencia";
|
||||
import { localDeIso, minAHora } from "../../lib/agendador";
|
||||
|
||||
const ESTADO = { participo: "✓ Participó", participara: "◷ Participará" };
|
||||
const hora = (a) => {
|
||||
const iso = a.tipo === "Tarea" ? a.scheduledend : a.scheduledstart || a.scheduledend;
|
||||
return iso ? minAHora(localDeIso(iso).min) : "";
|
||||
};
|
||||
|
||||
// Celda «Gerencia Comercial» de una fila del plan: por cada actividad de la fila donde participa Gerencia, su estado
|
||||
// (participó / participará) y su modalidad (presencial, virtual o llamada). «—» si no participa en ninguna.
|
||||
export default function GerenciaCelda({ acts }) {
|
||||
const items = (acts || []).map((a) => ({ a, g: gcDe(a) })).filter((x) => x.g);
|
||||
if (!items.length) return <span className="gc-nada">—</span>;
|
||||
return (
|
||||
<span className="gc-celda">
|
||||
{items.map(({ a, g }) => (
|
||||
<span key={a.id} className={`gc-chip ${g.estado}`} title={`${a.tipo === "Cita" ? "Visita" : a.tipo}: ${a.asunto || ""}`}>
|
||||
{ESTADO[g.estado]} · {ETIQUETA_MODALIDAD[g.modalidad] || a.tipo} {hora(a)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
21
app/components/plan/GerenciaResumen.js
Normal file
21
app/components/plan/GerenciaResumen.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import Link from "next/link";
|
||||
import { resumenGC } from "../../lib/gerencia";
|
||||
|
||||
// Tarjeta «Gerencia Comercial» del plan (día o periodo): en cuántas actividades participó y en cuántas participará, con el
|
||||
// desglose presencial / virtual. `acts`: actividades de las filas del plan. `hrefFiltro`: enlace que activa o quita el filtro
|
||||
// «solo donde participa Gerencia».
|
||||
export default function GerenciaResumen({ acts, hrefFiltro, filtrado }) {
|
||||
const r = resumenGC(acts);
|
||||
return (
|
||||
<div className="kpi kpi-gc">
|
||||
<span className="n">
|
||||
{r.participo} <small>participó</small> · {r.participara} <small>participará</small>
|
||||
</span>
|
||||
<span className="l">
|
||||
Gerencia Comercial · Presenciales {r.presencial} · Virtuales {r.virtualesTotal}
|
||||
{r.virtualesTotal ? ` (${r.virtual} Teams + ${r.llamada} llamada${r.llamada === 1 ? "" : "s"})` : ""}
|
||||
</span>
|
||||
<Link className="gc-filtro no-print" href={hrefFiltro}>{filtrado ? "Quitar filtro" : "Ver solo donde participa"}</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
92
app/components/plan/PlanSeccion.js
Normal file
92
app/components/plan/PlanSeccion.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { money, registroUrl } from "../../lib/constants";
|
||||
import { diaCorto } from "../../lib/plan";
|
||||
import AccionesFila from "./AccionesFila";
|
||||
import GerenciaCelda from "./GerenciaCelda";
|
||||
|
||||
// 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 ? 9 : 8;
|
||||
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>Gerencia Comercial</th>
|
||||
<th className="plan-estado">Estado</th>
|
||||
<th className="no-print">Acciones</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><GerenciaCelda acts={r.acts} /></td>
|
||||
<td className="plan-estado">
|
||||
{r.estado === "Completada" ? "✓ Completada" : r.estado}
|
||||
{r.total > 1 ? ` (${r.hechas}/${r.total})` : ""}
|
||||
</td>
|
||||
<td className="no-print">
|
||||
<AccionesFila acts={r.acts} opp={{ ...r.opp, ownerName: r.owner }} />
|
||||
</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 />
|
||||
<td />
|
||||
<td className="no-print" />
|
||||
</tr>
|
||||
</tfoot>
|
||||
)}
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
69
app/components/plan/PlanSeccionDia.js
Normal file
69
app/components/plan/PlanSeccionDia.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { money, registroUrl } from "../../lib/constants";
|
||||
import { actividadesTxt, etiquetasGV, actsDeSeccion, txtActividades } from "../../lib/planDia";
|
||||
import AccionesFila from "./AccionesFila";
|
||||
import SeccionPlegable from "./SeccionPlegable";
|
||||
|
||||
// Sección del Plan del Día (solo /plan; el Plan de Actividades sigue con PlanSeccion). Menos columnas que antes:
|
||||
// - «Ejecutivo» solo cuando se ven varios (`conEjecutivo`);
|
||||
// - Gerencia Comercial pasa a etiqueta «GV-Virtual» / «GV-Presencial» junto al cliente (en papel, a su propia columna);
|
||||
// - el estado desaparece: la fila completada queda atenuada con ✓; «Actividad» lleva la hora.
|
||||
export default function PlanSeccionDia({ seccion, conEjecutivo }) {
|
||||
const { key, titulo, sub, filas, subtotal } = seccion;
|
||||
const n = actsDeSeccion(seccion);
|
||||
if (!filas.length) {
|
||||
return <SeccionPlegable id={key} claseSec={key} titulo={titulo} resumen="Sin actividades agendadas" vacia />;
|
||||
}
|
||||
return (
|
||||
<SeccionPlegable id={key} claseSec={key} titulo={titulo} resumen={`${txtActividades(n)} · ${money(subtotal)}`} sub={sub}>
|
||||
<div className="ts">
|
||||
<table className={`plan-dia-tbl ${conEjecutivo ? "con-ej" : "sin-ej"}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="c-cli">Cliente</th>
|
||||
{conEjecutivo && <th className="c-eje">Ejecutivo</th>}
|
||||
<th className="c-obj">Objetivo del día</th>
|
||||
<th className="c-act">Actividad</th>
|
||||
<th className="num c-mrr">MRR</th>
|
||||
<th className="solo-print c-ger">Gerencia</th>
|
||||
<th className="no-print">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filas.map((r) => {
|
||||
const gv = etiquetasGV(r.acts);
|
||||
return (
|
||||
<tr key={r.key} className={r.estado === "Completada" ? "plan-hecha" : r.estado === "Vencida" ? "plan-venc" : ""}>
|
||||
<td>
|
||||
{r.estado === "Completada" && <span className="plan-check" title="Completada">✓ </span>}
|
||||
<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>}
|
||||
{gv.map((g) => <span key={g.k} className={`gv-tag ${g.k} gv-inline`}>{g.txt}</span>)}
|
||||
</td>
|
||||
{conEjecutivo && <td>{r.owner}</td>}
|
||||
<td>{r.objetivos.join(" · ")}</td>
|
||||
<td>{actividadesTxt(r.acts)}</td>
|
||||
<td className="num">{r.opp.valor == null ? "—" : money(r.opp.valor)}</td>
|
||||
<td className="solo-print">{gv.length ? gv.map((g) => <span key={g.k} className="gv-linea">{g.txt}</span>) : "—"}</td>
|
||||
<td className="no-print">
|
||||
<AccionesFila acts={r.acts} opp={{ ...r.opp, ownerName: r.owner }} />
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan={conEjecutivo ? 4 : 3} className="num"><strong>Total {titulo.toLowerCase()}</strong></td>
|
||||
<td className="num"><strong>{money(subtotal)}</strong></td>
|
||||
<td className="solo-print" />
|
||||
<td className="no-print" />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</SeccionPlegable>
|
||||
);
|
||||
}
|
||||
76
app/components/plan/PlanSeccionPeriodo.js
Normal file
76
app/components/plan/PlanSeccionPeriodo.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { money, registroUrl } from "../../lib/constants";
|
||||
import { actividadesPeriodo, etiquetasGV, actsDeSeccion, txtActividades } from "../../lib/planDia";
|
||||
import { diaDe } from "../../lib/plan";
|
||||
import AccionesFila from "./AccionesFila";
|
||||
import SeccionPlegable from "./SeccionPlegable";
|
||||
|
||||
// Sección del Plan de Actividades (período). Mismo patrón que PlanSeccionDia, con columna «Actividad» que lista
|
||||
// día + tipo + hora de cada actividad de la fila (y marca «vencida» en rojo). Columnas de ancho fijo por clase
|
||||
// (`pa-tbl`) para que se alineen entre secciones. En papel, Gerencia va en su propia columna.
|
||||
export default function PlanSeccionPeriodo({ seccion, conEjecutivo, hoy }) {
|
||||
const { key, titulo, sub, filas, subtotal } = seccion;
|
||||
const n = actsDeSeccion(seccion);
|
||||
if (!filas.length) {
|
||||
return <SeccionPlegable id={key} claseSec={key} titulo={titulo} resumen="Sin actividades agendadas" vacia />;
|
||||
}
|
||||
return (
|
||||
<SeccionPlegable id={key} claseSec={key} titulo={titulo} resumen={`${txtActividades(n)} · ${money(subtotal)}`} sub={sub}>
|
||||
<div className="ts">
|
||||
<table className={`plan-dia-tbl pa-tbl ${conEjecutivo ? "con-ej" : "sin-ej"}`}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="c-cli">Cliente</th>
|
||||
{conEjecutivo && <th className="c-eje">Ejecutivo</th>}
|
||||
<th className="c-obj">Objetivo</th>
|
||||
<th className="c-act">Actividad</th>
|
||||
<th className="num c-mrr">MRR</th>
|
||||
<th className="solo-print c-ger">Gerencia</th>
|
||||
<th className="no-print c-acc">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filas.map((r) => {
|
||||
const gv = etiquetasGV(r.acts);
|
||||
return (
|
||||
<tr key={r.key} className={r.estado === "Completada" ? "plan-hecha" : r.estado === "Vencida" ? "plan-venc" : ""}>
|
||||
<td>
|
||||
{r.estado === "Completada" && <span className="plan-check" title="Completada">✓ </span>}
|
||||
<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>}
|
||||
{gv.map((g) => <span key={g.k} className={`gv-tag ${g.k} gv-inline`}>{g.txt}</span>)}
|
||||
</td>
|
||||
{conEjecutivo && <td>{r.owner}</td>}
|
||||
<td>{r.objetivos.join(" · ")}</td>
|
||||
<td>
|
||||
{actividadesPeriodo(r.acts, diaDe, hoy).map((x) => (
|
||||
<span key={x.k} className="pa-act">
|
||||
{x.txt}
|
||||
{x.vencida && <span className="pa-venc"> · vencida</span>}
|
||||
</span>
|
||||
))}
|
||||
</td>
|
||||
<td className="num">{r.opp.valor == null ? "—" : money(r.opp.valor)}</td>
|
||||
<td className="solo-print">{gv.length ? gv.map((g) => <span key={g.k} className="gv-linea">{g.txt}</span>) : "—"}</td>
|
||||
<td className="no-print">
|
||||
<AccionesFila acts={r.acts} opp={{ ...r.opp, ownerName: r.owner }} />
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td colSpan={conEjecutivo ? 4 : 3} className="num"><strong>Total {titulo.toLowerCase()}</strong></td>
|
||||
<td className="num"><strong>{money(subtotal)}</strong></td>
|
||||
<td className="solo-print" />
|
||||
<td className="no-print" />
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</SeccionPlegable>
|
||||
);
|
||||
}
|
||||
59
app/components/plan/PlanTarjetasDia.js
Normal file
59
app/components/plan/PlanTarjetasDia.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import Link from "next/link";
|
||||
import { money } from "../../lib/constants";
|
||||
import { resumenGC } from "../../lib/gerencia";
|
||||
import { txtActividades, txtTipos } from "../../lib/planDia";
|
||||
|
||||
// Franja de tarjetas del Plan del Día, en una sola fila: Actividades planificadas · MRR en juego hoy · Gerencia Comercial
|
||||
// (toda la tarjeta es el enlace del filtro ?gc=1) · Ventas del mes · Renovaciones del mes (secundarias). Solo /plan; el Plan
|
||||
// de Actividades conserva su franja propia. No muestra «completadas»: el plan del día no evalúa cumplimiento.
|
||||
// `actsGC`: actividades del plan sin filtrar (para que el número de la tarjeta no cambie al activar el filtro).
|
||||
export default function PlanTarjetasDia({ actTotal, tipos, mrr, actsGC, hrefGC, filtrado, ventas, renov, fechaTxt, hechas = 0, vencidas = 0, className = "" }) {
|
||||
const gc = resumenGC(actsGC);
|
||||
const virtuales = gc.virtualesTotal;
|
||||
return (
|
||||
<div className={`kpis plan-kpis plan-kpis-dia ${className}`}>
|
||||
<div className="kpi">
|
||||
<span className="l t">Actividades planificadas</span>
|
||||
<span className="n">{actTotal}</span>
|
||||
<span className="l d">{txtTipos(tipos)}</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="l t">MRR en juego hoy</span>
|
||||
<span className="n">{money(mrr)}</span>
|
||||
<span className="l d">de las oportunidades con actividad</span>
|
||||
</div>
|
||||
<Link
|
||||
href={hrefGC}
|
||||
className={`kpi kpi-gc kpi-gc-link${filtrado ? " activo" : ""}`}
|
||||
aria-pressed={filtrado}
|
||||
title={filtrado ? "Quitar el filtro de Gerencia Comercial" : "Ver solo donde participa Gerencia Comercial"}
|
||||
>
|
||||
<span className="l t">Gerencia Comercial</span>
|
||||
<span className="n">{gc.total}</span>
|
||||
<span className="l d">
|
||||
{virtuales} {virtuales === 1 ? "virtual" : "virtuales"} · {gc.presencial} {gc.presencial === 1 ? "presencial" : "presenciales"}
|
||||
</span>
|
||||
<span className="gc-filtro no-print">{filtrado ? "Quitar filtro" : gc.total ? `Ver solo estas ${txtActividades(gc.total)}` : "Sin actividades con Gerencia"}</span>
|
||||
</Link>
|
||||
{/* Solo pantalla: en el PDF esta tarjeta no sale (el PDF conserva Ventas y Renovaciones del mes, como siempre). */}
|
||||
<div className="kpi kpi-hechas no-print">
|
||||
<span className="l t">Hechas · vencidas</span>
|
||||
<span className="n">{hechas} de {actTotal}</span>
|
||||
<span className="l d">
|
||||
{hechas === 1 ? "hecha" : "hechas"} · <span className={vencidas ? "pa-venc" : ""}>{vencidas} {vencidas === 1 ? "vencida" : "vencidas"}</span>
|
||||
</span>
|
||||
</div>
|
||||
{/* Solo PDF: en pantalla las reemplaza «Hechas · vencidas». */}
|
||||
<div className="kpi kpi-sec kpi-solo-pdf">
|
||||
<span className="l t">Ventas del mes</span>
|
||||
<span className="n">{money(ventas)}</span>
|
||||
<span className="l d">al {fechaTxt}</span>
|
||||
</div>
|
||||
<div className="kpi kpi-sec kpi-solo-pdf">
|
||||
<span className="l t">Renovaciones del mes</span>
|
||||
<span className="n">{money(renov)}</span>
|
||||
<span className="l d">al {fechaTxt}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
app/components/plan/PlanTarjetasPeriodo.js
Normal file
73
app/components/plan/PlanTarjetasPeriodo.js
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import Link from "next/link";
|
||||
import { money } from "../../lib/constants";
|
||||
import { resumenGC } from "../../lib/gerencia";
|
||||
import { txtActividades, txtTipos } from "../../lib/planDia";
|
||||
|
||||
// Franja de 4 tarjetas del Plan de Actividades (mismo estilo que PlanTarjetasDia, sin tocarla):
|
||||
// Actividades planificadas · MRR en juego en el período · Gerencia Comercial (enlace del filtro ?gc=1) ·
|
||||
// Avance (cumplimiento a la fecha; enlace del filtro ?venc=1). Todos los números salen del plan SIN filtrar,
|
||||
// así no cambian al activar un filtro.
|
||||
// `r`: resumen de armarPlanPeriodo; `actsGC`: actividades del plan sin filtrar.
|
||||
export default function PlanTarjetasPeriodo({ actTotal, tipos, mrr, actsGC, hrefGC, filtradoGC, r, hrefVenc, filtradoVenc, className = "" }) {
|
||||
const gc = resumenGC(actsGC);
|
||||
const virtuales = gc.virtualesTotal;
|
||||
const pct = r.pctFecha;
|
||||
const detalleAvance = r.debidas ? (
|
||||
<>
|
||||
{r.debidasHechas} de {r.debidas} completadas de los días anteriores a hoy ·{" "}
|
||||
<span className={r.vencidas ? "pa-venc" : ""}>{r.vencidas} {r.vencidas === 1 ? "vencida" : "vencidas"}</span>
|
||||
</>
|
||||
) : (
|
||||
"Aún no hay días anteriores a hoy en el período"
|
||||
);
|
||||
const cuerpoAvance = (
|
||||
<>
|
||||
<span className="l t">Avance · cumplimiento a la fecha</span>
|
||||
<span className="n">{pct == null ? "—" : `${pct.toFixed(1)}%`}</span>
|
||||
<span className="l d">{detalleAvance}</span>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<div className={`kpis plan-kpis plan-kpis-dia plan-kpis-per ${className}`}>
|
||||
<div className="kpi">
|
||||
<span className="l t">Actividades planificadas</span>
|
||||
<span className="n">{actTotal}</span>
|
||||
<span className="l d">{txtTipos(tipos)}</span>
|
||||
</div>
|
||||
<div className="kpi">
|
||||
<span className="l t">MRR en juego en el período</span>
|
||||
<span className="n">{money(mrr)}</span>
|
||||
<span className="l d">de las oportunidades con actividad</span>
|
||||
</div>
|
||||
<Link
|
||||
href={hrefGC}
|
||||
className={`kpi kpi-gc kpi-gc-link${filtradoGC ? " activo" : ""}`}
|
||||
aria-pressed={filtradoGC}
|
||||
title={filtradoGC ? "Quitar el filtro de Gerencia Comercial" : "Ver solo donde participa Gerencia Comercial"}
|
||||
>
|
||||
<span className="l t">Gerencia Comercial</span>
|
||||
<span className="n">{gc.total}</span>
|
||||
<span className="l d">
|
||||
{virtuales} {virtuales === 1 ? "virtual" : "virtuales"} · {gc.presencial} {gc.presencial === 1 ? "presencial" : "presenciales"}
|
||||
</span>
|
||||
<span className="gc-filtro no-print">{filtradoGC ? "Quitar filtro" : gc.total ? `Ver solo estas ${txtActividades(gc.total)}` : "Sin actividades con Gerencia"}</span>
|
||||
</Link>
|
||||
{r.vencidas || filtradoVenc ? (
|
||||
<Link
|
||||
href={hrefVenc}
|
||||
className={`kpi kpi-gc-link${filtradoVenc ? " activo" : ""}`}
|
||||
aria-pressed={filtradoVenc}
|
||||
title={filtradoVenc ? "Quitar el filtro de vencidas" : "Ver solo las filas con actividades vencidas"}
|
||||
>
|
||||
{cuerpoAvance}
|
||||
<span className="gc-filtro no-print">{filtradoVenc ? "Quitar filtro" : `Ver solo las ${r.vencidas} ${r.vencidas === 1 ? "vencida" : "vencidas"}`}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="kpi">
|
||||
{cuerpoAvance}
|
||||
{r.debidas > 0 && <span className="gc-filtro no-print pa-sinvenc">Sin vencidas</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
37
app/components/plan/SeccionPlegable.js
Normal file
37
app/components/plan/SeccionPlegable.js
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
"use client";
|
||||
import { useState } from "react";
|
||||
|
||||
// Contenedor de una sección del Plan del Día: el encabezado pliega o despliega el cuerpo (la tabla, que llega ya armada
|
||||
// desde el servidor como `children`). Por defecto desplegada. En el PDF el CSS muestra siempre el cuerpo.
|
||||
// `vacia`: sin actividades → solo una línea, sin botón ni tabla.
|
||||
export default function SeccionPlegable({ id, claseSec, titulo, resumen, vacia = false, sub, children }) {
|
||||
const [abierta, setAbierta] = useState(true);
|
||||
return (
|
||||
<section id={`sec-${id}`} className={`plan-sec plan-sec-dia sec-${claseSec}${vacia ? " vacia" : ""}${abierta ? "" : " plegada"}`}>
|
||||
{vacia ? (
|
||||
<div className="plan-sec-head">
|
||||
<span className="plan-sec-t" role="heading" aria-level={3}>{titulo}</span>
|
||||
<span className="plan-sec-cnt plan-sec-vacia">{resumen}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="plan-sec-head plan-sec-toggle"
|
||||
aria-expanded={abierta}
|
||||
aria-controls={`cuerpo-${id}`}
|
||||
onClick={() => setAbierta((v) => !v)}
|
||||
>
|
||||
<span className="plan-sec-flecha no-print" aria-hidden="true">{abierta ? "▾" : "▸"}</span>
|
||||
<span className="plan-sec-t" role="heading" aria-level={3}>{titulo}</span>
|
||||
<span className="plan-sec-cnt">{resumen}</span>
|
||||
</button>
|
||||
<div id={`cuerpo-${id}`} className="plan-sec-cuerpo">
|
||||
{sub && <div className="plan-sec-sub no-print">{sub}</div>}
|
||||
{children}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
114
app/components/plan/SinActividadPanel.js
Normal file
114
app/components/plan/SinActividadPanel.js
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { money, registroUrl } from "../../lib/constants";
|
||||
import AgendarBoton from "../actividades/AgendarBoton";
|
||||
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>
|
||||
<AgendarBoton opp={o} />
|
||||
</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>
|
||||
);
|
||||
}
|
||||
144
app/cuentas/[id]/page.js
Normal file
144
app/cuentas/[id]/page.js
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import Link from "next/link";
|
||||
import { auth } from "../../lib/auth";
|
||||
import { leerCuenta, esGuid } from "../../lib/cuentasServer";
|
||||
import { hoyManagua } from "../../lib/plan";
|
||||
import { esAsistente } from "../../lib/authz";
|
||||
import { resolveOwnerId } from "../../lib/queries";
|
||||
import { money, registroUrl, DYN } from "../../lib/constants";
|
||||
import LoginPrompt from "../../components/LoginPrompt";
|
||||
import ErrorNotice from "../../components/ErrorNotice";
|
||||
import NuevaActividadBoton from "../../components/actividades/NuevaActividadBoton";
|
||||
import GestionarActividad from "../../components/actividades/GestionarActividad";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const fecha = (iso) => (iso ? `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}` : "—");
|
||||
// Fecha de Nicaragua (UTC-6) de un instante ISO.
|
||||
const diaLocal = (iso) => (iso ? new Date(new Date(iso).getTime() - 6 * 3600 * 1000).toISOString().slice(0, 10) : null);
|
||||
|
||||
export default async function CuentaPage({ params }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
const { id } = await params;
|
||||
if (!esGuid(id)) return <div style={{ padding: 24 }}><p>Cuenta no válida. <Link href="/cuentas">Volver a Cuentas</Link></p></div>;
|
||||
|
||||
let c;
|
||||
try {
|
||||
c = await leerCuenta(session.accessToken, id);
|
||||
} catch (error) {
|
||||
if (String(error?.message || "").includes("DATAVERSE_404")) return <div style={{ padding: 24 }}><p>No encontré esa cuenta. <Link href="/cuentas">Volver a Cuentas</Link></p></div>;
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
// Ejecutivo: solo las cuentas de las que es propietario. Gerente y asistente de ventas: todas.
|
||||
if (!(session.isAdmin || esAsistente(session.email))) {
|
||||
const mio = await resolveOwnerId(session.email, session.accessToken);
|
||||
if (!mio || mio !== c.propietarioId) {
|
||||
return <div style={{ padding: 24 }}><p>No tienes acceso a esta cuenta: solo puedes ver las cuentas de las que eres propietario. <Link href="/cuentas">Volver a Cuentas</Link></p></div>;
|
||||
}
|
||||
}
|
||||
const mrr = c.oportunidades.reduce((a, o) => a + (o.valor || 0), 0);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<p style={{ margin: 0 }}><Link href="/cuentas">← Cuentas</Link></p>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", flexWrap: "wrap", gap: 12, margin: "6px 0 14px" }}>
|
||||
<div>
|
||||
<h2 style={{ margin: 0 }}>{c.nombre}{c.vip ? " ⭐" : ""}</h2>
|
||||
{c.comercial && <div className="hint" style={{ margin: 0 }}>{c.comercial}</div>}
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
|
||||
<NuevaActividadBoton hoy={hoyManagua()} referente={{ tipo: "account", id: c.id, nombre: c.nombre }} oportunidades={c.oportunidades.map((o) => ({ id: o.id, nombre: o.nombre }))} />
|
||||
<a className="gst-sec-btn" style={{ padding: "8px 14px", textDecoration: "none" }} href={registroUrl("account", c.id)} target="_blank" rel="noopener">Abrir en Dynamics ↗</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{c.oportunidades.length}</span><span className="l">Oportunidades abiertas</span></div>
|
||||
<div className="kpi"><span className="n">{money(mrr)}</span><span className="l">Valor estimado abierto</span></div>
|
||||
<div className="kpi"><span className="n">{c.contactos.length}</span><span className="l">Contactos activos</span></div>
|
||||
{c.puntuacion != null && <div className="kpi"><span className="n">{Math.round(c.puntuacion)}</span><span className="l">Puntuación de la cuenta</span></div>}
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Datos de la cuenta</h3>
|
||||
<table className="cta-tabla">
|
||||
<tbody>
|
||||
{[
|
||||
["Propietario", c.propietario],
|
||||
["Tipo de relación", c.tipo],
|
||||
["Nivel", c.nivel],
|
||||
["Clasificación", c.clasificacion],
|
||||
["Teléfono", c.telefono],
|
||||
["Correo", c.correo],
|
||||
["Dirección", [c.direccion, c.ciudad].filter(Boolean).join(", ")],
|
||||
["Creada", c.creada ? fecha(c.creada) : null],
|
||||
].map(([k, v]) => (
|
||||
<tr key={k}><th style={{ width: 160, textAlign: "left" }}>{k}</th><td>{v || "—"}</td></tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Oportunidades abiertas ({c.oportunidades.length})</h3>
|
||||
{c.oportunidades.length ? (
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Oportunidad</th><th>Tipo</th><th>Forecast</th><th className="num">MRR est.</th><th>Cierre est.</th><th>Propietario</th></tr></thead>
|
||||
<tbody>
|
||||
{c.oportunidades.map((o) => (
|
||||
<tr key={o.id}>
|
||||
<td><a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.nombre}</a></td>
|
||||
<td>{o.tipo || "—"}</td>
|
||||
<td>{o.forecast || "—"}</td>
|
||||
<td className="num">{money(o.valor)}</td>
|
||||
<td>{fecha(o.cierre)}</td>
|
||||
<td>{o.propietario || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : <p className="hint" style={{ margin: 0 }}>Sin oportunidades abiertas.</p>}
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Contactos ({c.contactos.length})</h3>
|
||||
{c.contactos.length ? (
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Nombre</th><th>Cargo</th><th>Correo</th><th>Teléfono</th></tr></thead>
|
||||
<tbody>
|
||||
{c.contactos.map((k, i) => (
|
||||
<tr key={i}><td>{k.nombre}</td><td>{k.cargo || "—"}</td><td>{k.correo || "—"}</td><td>{k.movil || "—"}</td></tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : <p className="hint" style={{ margin: 0 }}>Sin contactos activos registrados.</p>}
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Últimas actividades</h3>
|
||||
<p className="hint">De la cuenta y de sus oportunidades abiertas. Haz clic en una abierta para gestionarla.</p>
|
||||
{c.actividades.length ? (
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Tipo</th><th>Asunto</th><th>Referente</th><th>Fecha</th><th>Estado</th><th>Propietario</th></tr></thead>
|
||||
<tbody>
|
||||
{c.actividades.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td>{a.tipo === "Cita" ? "Visita" : a.tipo}</td>
|
||||
<td>
|
||||
{a.estado === "abierta" ? (
|
||||
<GestionarActividad a={{ ...a, referente: null }} className="gst-link" title={a.asunto}>{a.asunto}</GestionarActividad>
|
||||
) : a.asunto}
|
||||
</td>
|
||||
<td className="elip">{a.referente || "—"}</td>
|
||||
<td>{fecha(diaLocal(a.scheduledend || a.scheduledstart))}</td>
|
||||
<td>{a.estado}</td>
|
||||
<td>{a.owner || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
) : <p className="hint" style={{ margin: 0 }}>Sin actividades registradas.</p>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
126
app/cuentas/cuentasActions.js
Normal file
126
app/cuentas/cuentasActions.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
"use server";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { auth } from "../lib/auth";
|
||||
import { esAsistente } from "../lib/authz";
|
||||
import { resolveOwnerId } from "../lib/queries";
|
||||
import { hoyManagua, addDays } from "../lib/plan";
|
||||
import { TIPOS_AGENDADOR, OBJETIVOS_LIBRES, horaAMin, localDeIso, fechaMaxima, asuntoDe, actividadParaDe } from "../lib/agendador";
|
||||
import { objetivosPorNombre, oportunidadesFrescas } from "../lib/agendadorServer";
|
||||
import { buscarCuentas, buscarOportunidades, crearActividadLibre, esGuid } from "../lib/cuentasServer";
|
||||
import { dvFresh } from "../lib/dataverse";
|
||||
import { registrarAccion } from "../lib/actividadAcciones";
|
||||
import { leerActividad, completarActividad, leerParticipacionOpp, sumarParticipacionOpp } from "../lib/actividadesServer";
|
||||
import { CODIGOS } from "../lib/participantes";
|
||||
import { aUtc, minAHora } from "../lib/agendador";
|
||||
|
||||
const apagado = () => String(process.env.ACTIVIDADES_ACCIONES || "").toLowerCase() === "off";
|
||||
const DURACIONES = { Llamada: [15, 30, 45, 60], Cita: [30, 60, 90, 120] };
|
||||
|
||||
// Busca, para ligarles una actividad, oportunidades abiertas (las del propio ejecutivo) y cuentas.
|
||||
export async function buscarReferentesAction(q) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
try {
|
||||
const mio = await resolveOwnerId(session.email, session.accessToken);
|
||||
// Gerente y asistente de ventas ven todo; el ejecutivo, solo sus oportunidades y cuentas.
|
||||
const veTodo = session.isAdmin || esAsistente(session.email);
|
||||
const [opps, cuentas] = await Promise.all([
|
||||
buscarOportunidades(session.accessToken, q, veTodo ? null : mio),
|
||||
buscarCuentas(session.accessToken, q, 8, veTodo ? null : mio),
|
||||
]);
|
||||
return { ok: true, opps, cuentas };
|
||||
} catch (e) {
|
||||
console.error("[cuentas] buscar", String(e?.message || e).slice(0, 300));
|
||||
return e?.message === "TOKEN_EXPIRED" ? { ok: false, error: "Tu sesión expiró. Vuelve a iniciar sesión." } : { ok: false, error: "No pude buscar en Dynamics. Intenta de nuevo." };
|
||||
}
|
||||
}
|
||||
|
||||
// Crea una actividad (llamada, cita o tarea) a nombre del usuario que la pide, ligada a una oportunidad o a
|
||||
// una cuenta. El navegador solo dice QUÉ quiere; permisos, estado y fechas se vuelven a validar aquí.
|
||||
export async function crearActividadLibreAction({ tipo, referenteTipo, referenteId, objetivo, dia, hora, duracion, realizada = false, nota = "", participantes = [], enNombreDe = false, modalidad = "presencial", canal = "web" }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return { ok: false, error: "Inicia sesión." };
|
||||
if (apagado()) return { ok: false, error: "La gestión de actividades está en pausa por mantenimiento." };
|
||||
if (!TIPOS_AGENDADOR.includes(tipo) || !["opportunity", "account"].includes(referenteTipo) || !esGuid(referenteId)) return { ok: false, error: "Solicitud no válida." };
|
||||
if (!OBJETIVOS_LIBRES.includes(String(objetivo || ""))) return { ok: false, error: "Elige un objetivo." };
|
||||
const hoy = hoyManagua();
|
||||
const yaHecha = realizada === true;
|
||||
const desde = yaHecha ? addDays(hoy, -30) : hoy;
|
||||
const hasta = yaHecha ? hoy : fechaMaxima(hoy);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(dia || "")) || dia < desde || dia > hasta) {
|
||||
return { ok: false, error: yaHecha ? "Una actividad ya realizada debe tener fecha de hoy o de los últimos 30 días." : "La fecha debe estar entre hoy y los próximos 30 días." };
|
||||
}
|
||||
const m = horaAMin(String(hora || ""));
|
||||
if (m == null || m < 360 || m > 1200) return { ok: false, error: "Elige una hora entre 6:00 y 20:00." };
|
||||
if (!yaHecha && dia === hoy && m < localDeIso(new Date().toISOString()).min) return { ok: false, error: "Esa hora ya pasó." };
|
||||
if (yaHecha && dia === hoy && m > localDeIso(new Date().toISOString()).min) return { ok: false, error: "Una actividad ya realizada no puede tener una hora futura." };
|
||||
const texto = String(nota || "").slice(0, 1500);
|
||||
const roles = (Array.isArray(participantes) ? participantes : []).map(String).filter((c) => CODIGOS.includes(c));
|
||||
const dur = tipo === "Tarea" ? 0 : DURACIONES[tipo].includes(Number(duracion)) ? Number(duracion) : tipo === "Cita" ? 60 : 30;
|
||||
if (tipo !== "Tarea" && m + dur > 1260) return { ok: false, error: "La actividad terminaría muy tarde; elige una hora más temprano." };
|
||||
|
||||
try {
|
||||
const token = session.accessToken;
|
||||
let ownerId = await resolveOwnerId(session.email, token);
|
||||
if (!ownerId) return { ok: false, error: "No encontré tu usuario en Dynamics." };
|
||||
const objetivos = await objetivosPorNombre(token);
|
||||
const objetivoId = objetivos.get(objetivo);
|
||||
if (!objetivoId) return { ok: false, error: "No encontré ese objetivo en Dynamics." };
|
||||
|
||||
let nombre;
|
||||
let actividadPara;
|
||||
if (referenteTipo === "opportunity") {
|
||||
const o = (await oportunidadesFrescas(token, [referenteId])).get(referenteId);
|
||||
if (!o || !o.abierta) return { ok: false, error: "La oportunidad no está abierta." };
|
||||
nombre = o.nombre;
|
||||
actividadPara = actividadParaDe(o.tipoCodigo);
|
||||
// Desde las tablas de oportunidades la actividad queda a nombre del PROPIETARIO de la oportunidad (como hacía
|
||||
// el enlace a Dynamics). Solo el propio dueño, el administrador o la asistente de ventas pueden hacerlo.
|
||||
if (!enNombreDe && o.ownerId && o.ownerId !== ownerId && !(session.isAdmin || esAsistente(session.email))) return { ok: false, error: "Solo puedes agendar en tus propias oportunidades." };
|
||||
if (enNombreDe && o.ownerId && o.ownerId !== ownerId) {
|
||||
if (!(session.isAdmin || esAsistente(session.email))) return { ok: false, error: "Solo puedes agendar en tus propias oportunidades." };
|
||||
ownerId = o.ownerId;
|
||||
}
|
||||
} else {
|
||||
const c = await dvFresh(`accounts(${referenteId})?$select=name,customertypecode,statecode,_ownerid_value`, token);
|
||||
if (c.statecode !== 0) return { ok: false, error: "La cuenta no está activa." };
|
||||
if (!(session.isAdmin || esAsistente(session.email)) && c._ownerid_value !== ownerId) return { ok: false, error: "Solo puedes agendar en tus propias cuentas." };
|
||||
nombre = c.name;
|
||||
// Cliente (3) → Cliente Activo; prospecto u otro → Cliente Nuevo.
|
||||
actividadPara = c.customertypecode === 3 ? 100000000 : 100000001;
|
||||
}
|
||||
// Canal «whatsapp» (app de campo): el asunto lo indica, para distinguir estas llamadas registradas de las hechas por teléfono.
|
||||
const asunto = (canal === "whatsapp" ? "WhatsApp – " : "") + asuntoDe({ tipo, objetivo, cliente: nombre, nombre });
|
||||
const id = await crearActividadLibre(token, { tipo, referenteTipo, referenteId, asunto, objetivoId, ownerId, dia, hora, duracion: dur, actividadPara, participantes: yaHecha ? [] : roles, lugar: tipo === "Cita" ? (modalidad === "virtual" ? "Virtual" : "Oficina del cliente") : null });
|
||||
// «Ya la realicé»: se crea y se completa en el mismo paso, con la fecha real y la nota del resultado.
|
||||
let avisoOpp = null;
|
||||
let completada = false;
|
||||
if (yaHecha) {
|
||||
try {
|
||||
const act = await leerActividad(token, tipo, id);
|
||||
const fin = tipo === "Tarea" ? aUtc(dia, hora) : aUtc(dia, minAHora(m + dur));
|
||||
await completarActividad(token, act, texto, roles, fin);
|
||||
completada = true;
|
||||
if (roles.length && referenteTipo === "opportunity" && String(process.env.PARTICIPANTES_OPP || "").toLowerCase() !== "off") {
|
||||
try { await sumarParticipacionOpp(token, referenteId, roles); } catch { avisoOpp = "La actividad se registró, pero no pude actualizar la participación en la oportunidad."; }
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[cuentas] completar tras crear", String(e?.message || e).slice(0, 300));
|
||||
avisoOpp = "La actividad se creó pero no pude completarla; ábrela en la Agenda para completarla.";
|
||||
}
|
||||
}
|
||||
const accionId = registrarAccion({
|
||||
actor: session.email, ownerId, ownerName: null, tipo, activityId: id, accion: "creacion", resultado: "ok",
|
||||
previo: { referenteTipo, referenteId }, nuevo: { dia, hora, objetivo, duracion: dur, realizada: completada }, canal: ["whatsapp", "movil"].includes(canal) ? canal : "web",
|
||||
});
|
||||
["/", "/actividades", "/plan", "/agendador", "/cuentas", "/m/hoy", "/m/semana", "/m/calendario", "/m/tuberia"].forEach((p) => revalidatePath(p));
|
||||
return { ok: true, id, accionId, asunto, completada, avisoOpp };
|
||||
} catch (e) {
|
||||
const msg = String(e?.message || e);
|
||||
console.error("[cuentas] crear", JSON.stringify({ actor: session.email, tipo, referenteTipo, error: msg.slice(0, 400) }));
|
||||
try { registrarAccion({ actor: session.email, tipo, activityId: referenteId, accion: "creacion", resultado: "error", error: msg }); } catch { /* ignorar */ }
|
||||
if (msg === "TOKEN_EXPIRED") return { ok: false, error: "Tu sesión expiró. Vuelve a iniciar sesión y reintenta." };
|
||||
if (msg.includes("DATAVERSE_403")) return { ok: false, error: "Dynamics no te permite crear actividades para este registro." };
|
||||
return { ok: false, error: `No se pudo crear la actividad en Dynamics${msg.match(/DATAVERSE_(\d+)/) ? ` (código ${msg.match(/DATAVERSE_(\d+)/)[1]})` : ""}. Intenta de nuevo; si persiste, avisa a Marco.` };
|
||||
}
|
||||
}
|
||||
66
app/cuentas/page.js
Normal file
66
app/cuentas/page.js
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
import Link from "next/link";
|
||||
import { auth } from "../lib/auth";
|
||||
import { buscarCuentas } from "../lib/cuentasServer";
|
||||
import { esAsistente } from "../lib/authz";
|
||||
import { resolveOwnerId } from "../lib/queries";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Cuentas del CRM: buscar una cuenta por nombre y abrir su ficha (datos, contactos, oportunidades, actividades).
|
||||
export default async function CuentasPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
const sp = await searchParams;
|
||||
const q = String(sp.q || "").trim().slice(0, 60);
|
||||
|
||||
let cuentas = null;
|
||||
if (q.length >= 2) {
|
||||
try {
|
||||
// Ejecutivo: solo sus cuentas. Gerente y asistente de ventas: todas.
|
||||
const veTodas = session.isAdmin || esAsistente(session.email);
|
||||
const mio = veTodas ? null : await resolveOwnerId(session.email, session.accessToken);
|
||||
cuentas = veTodas ? await buscarCuentas(session.accessToken, q, 30) : mio ? await buscarCuentas(session.accessToken, q, 30, mio) : [];
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Cuentas</h2>
|
||||
<p className="hint">Busca una cuenta del CRM para ver sus datos, contactos y oportunidades, y agregarle actividades.{session.isAdmin || esAsistente(session.email) ? "" : " Aquí aparecen las cuentas de las que eres propietario."}</p>
|
||||
<form method="get" className="busca-opp">
|
||||
<input type="search" name="q" defaultValue={q} placeholder="🔍 Nombre o nombre comercial de la cuenta…" aria-label="Buscar cuenta" autoFocus />
|
||||
<button type="submit" className="gst-go" style={{ padding: "8px 18px" }}>Buscar</button>
|
||||
</form>
|
||||
{q.length > 0 && q.length < 2 && <p className="hint">Escribe al menos 2 letras.</p>}
|
||||
{cuentas && (
|
||||
<div className="panel">
|
||||
<h3>{cuentas.length ? `${cuentas.length}${cuentas.length === 30 ? "+" : ""} cuenta${cuentas.length === 1 ? "" : "s"} para «${q}»` : `Sin cuentas para «${q}»`}</h3>
|
||||
{cuentas.length > 0 && (
|
||||
<table className="cta-tabla">
|
||||
<thead>
|
||||
<tr><th>Cuenta</th><th>Tipo</th><th>Propietario</th><th>Teléfono</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{cuentas.map((c) => (
|
||||
<tr key={c.id}>
|
||||
<td className="dual-cel">
|
||||
<Link className="opp" href={`/cuentas/${c.id}`}>{c.nombre}</Link>
|
||||
{c.comercial && <span className="sub">{c.comercial}</span>}
|
||||
</td>
|
||||
<td>{c.tipo || "—"}</td>
|
||||
<td>{c.propietario || "—"}</td>
|
||||
<td>{c.telefono || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
233
app/equipo/page.js
Normal file
233
app/equipo/page.js
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import Link from "next/link";
|
||||
import { auth } from "../lib/auth";
|
||||
import {
|
||||
getActividades, getPipeline, getRenovPipeline, getClosedRange, getSystemUsers, VENTA_TYPE_FILTER, REN_TYPE_FILTER,
|
||||
} from "../lib/queries";
|
||||
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
||||
import { getMetas } from "../lib/metas";
|
||||
import { hoyManagua, addDays, semanaDe, diaCorto } from "../lib/plan";
|
||||
import { armarEquipo, totalEquipo, pct } from "../lib/equipo";
|
||||
import { diasActivosPorEmail } from "../lib/uso";
|
||||
import { money, DYN } from "../lib/constants";
|
||||
import LoginPrompt from "../components/LoginPrompt";
|
||||
import ErrorNotice from "../components/ErrorNotice";
|
||||
import AgendarBoton from "../components/actividades/AgendarBoton";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Mismas reglas que Previsión para el forecast del mes (ventas con plan A/B/C).
|
||||
const PREVIS_TIPOS = ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling"];
|
||||
const PREVIS_PLANES_EXCL = ["Sin plan de cierre", "Plan D - Recalificar"];
|
||||
const MESES = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
|
||||
const fecha = (iso) => iso.split("-").reverse().join("/");
|
||||
const suma = (rows) => rows.reduce((t, o) => t + (o.actual || 0), 0);
|
||||
|
||||
function mesDe(hoy, off) {
|
||||
const [y, m] = hoy.split("-").map(Number);
|
||||
const d = new Date(Date.UTC(y, m - 1 + off, 1));
|
||||
const ini = d.toISOString().slice(0, 10);
|
||||
const fin = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).toISOString().slice(0, 10);
|
||||
return { ini, fin, etiqueta: `${MESES[d.getUTCMonth()]} ${d.getUTCFullYear()}` };
|
||||
}
|
||||
|
||||
// Vista del equipo para el gerente (lunes: plan de la semana y del mes; sábado: tubería al día y actividades
|
||||
// planificadas). Solo administradores. Todo se mide con lo registrado en el CRM: WhatsApp no está integrado.
|
||||
export default async function EquipoPage({ searchParams }) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return <LoginPrompt />;
|
||||
if (!session.isAdmin) return <div style={{ padding: 24 }}><h2>Equipo</h2><p>Esta página es solo para el gerente.</p></div>;
|
||||
|
||||
const sp = await searchParams;
|
||||
const vista = sp.vista === "mes" ? "mes" : "semana";
|
||||
const off = Math.max(-1, Math.min(1, Number(sp.off) || 0));
|
||||
const hoy = hoyManagua();
|
||||
|
||||
let desde, hasta, etiqueta;
|
||||
if (vista === "semana") {
|
||||
const s = semanaDe(addDays(hoy, off * 7));
|
||||
desde = s.lunes; hasta = s.domingo;
|
||||
etiqueta = `${off === 0 ? "Esta semana" : off < 0 ? "Semana pasada" : "Próxima semana"} · ${fecha(desde)} al ${fecha(hasta)}`;
|
||||
} else {
|
||||
const m = mesDe(hoy, Math.min(off, 0));
|
||||
desde = m.ini; hasta = m.fin;
|
||||
etiqueta = `${off < 0 ? "Mes pasado" : "Este mes"} · ${m.etiqueta}`;
|
||||
}
|
||||
|
||||
const todos = { emails: [], locked: false };
|
||||
let users, actividades, pipeV, pipeR, ganV, ganR, perV, perR;
|
||||
try {
|
||||
const sigDia = addDays(hasta, 1);
|
||||
[users, actividades, pipeV, pipeR, ganV, ganR, perV, perR] = await Promise.all([
|
||||
getSystemUsers(session.accessToken),
|
||||
getActividades(session.accessToken, todos),
|
||||
getPipeline(session.accessToken, todos),
|
||||
getRenovPipeline(session.accessToken, todos),
|
||||
getClosedRange(session.accessToken, todos, 1, desde, sigDia, undefined, VENTA_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, todos, 1, desde, sigDia, undefined, REN_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, todos, 2, desde, sigDia, undefined, VENTA_TYPE_FILTER),
|
||||
getClosedRange(session.accessToken, todos, 2, desde, sigDia, undefined, REN_TYPE_FILTER),
|
||||
]);
|
||||
} catch (error) {
|
||||
return <ErrorNotice error={error} />;
|
||||
}
|
||||
|
||||
const nombres = EJECUTIVOS_VENTA;
|
||||
const emailDe = Object.fromEntries(users.filter((u) => nombres.includes(u.name)).map((u) => [u.name, (u.email || "").toLowerCase()]));
|
||||
const metas = getMetas();
|
||||
const por = armarEquipo({ nombres, actividades, opps: [...pipeV, ...pipeR], hoy, desde, hasta });
|
||||
const tot = totalEquipo(por);
|
||||
const uso = diasActivosPorEmail(desde, hasta > hoy ? hoy : hasta);
|
||||
const diasLab = []; // lunes a viernes de la semana
|
||||
if (vista === "semana") for (let d = desde, i = 0; i < 7; i++, d = addDays(d, 1)) diasLab.push(d);
|
||||
|
||||
// Resultados por ejecutivo (mes) y forecast del mes en curso.
|
||||
const porNombre = (rows, n) => rows.filter((o) => o.owner === n);
|
||||
const mesClave = hasta.slice(0, 7);
|
||||
const baseV = pipeV.filter((o) => PREVIS_TIPOS.includes(o.tipo) && !PREVIS_PLANES_EXCL.includes(o.plan));
|
||||
const resultados = nombres.map((n) => {
|
||||
const email = emailDe[n];
|
||||
const meta = metas[email] || null;
|
||||
const gv = suma(porNombre(ganV, n));
|
||||
const fcMes = baseV.filter((o) => o.owner === n && o.mesCierre === mesClave).reduce((a, o) => a + o.fc, 0);
|
||||
return {
|
||||
nombre: n, gv, gvN: porNombre(ganV, n).length, gr: suma(porNombre(ganR, n)), grN: porNombre(ganR, n).length,
|
||||
pv: suma(porNombre(perV, n).map((o) => ({ actual: o.est }))), pvN: porNombre(perV, n).length,
|
||||
pr: porNombre(perR, n).length, meta, fcMes, cobertura: meta ? Math.round(((gv + fcMes) / meta) * 100) : null,
|
||||
};
|
||||
});
|
||||
const casos = Object.values(por).flatMap((L) => L.casos).sort((a, b) => b.valor - a.valor).slice(0, 25);
|
||||
|
||||
const tabs = (v, o, l) => (
|
||||
<Link key={`${v}${o}`} href={`/equipo?vista=${v}&off=${o}`} className={vista === v && off === o ? "on" : ""} style={{ textDecoration: "none" }}>{l}</Link>
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24 }}>
|
||||
<h2>Equipo</h2>
|
||||
<p className="hint">
|
||||
Cómo fluye la actividad comercial de los {nombres.length} ejecutivos de venta. Solo cuenta lo registrado en el CRM: el seguimiento por WhatsApp no aparece aquí, así que
|
||||
«sin actividad» significa «sin actividad registrada en el CRM».
|
||||
</p>
|
||||
<div className="seccion-tabs" style={{ padding: 0 }}>
|
||||
<div className="seg-tabs">{tabs("semana", -1, "Semana pasada")}{tabs("semana", 0, "Esta semana")}{tabs("semana", 1, "Próxima semana")}</div>
|
||||
<div className="seg-tabs">{tabs("mes", 0, "Este mes")}{tabs("mes", -1, "Mes pasado")}</div>
|
||||
</div>
|
||||
<p style={{ fontWeight: 700, color: "#01205B" }}>{etiqueta}</p>
|
||||
|
||||
<div className="kpis">
|
||||
<div className="kpi"><span className="n">{tot.plan}</span><span className="l">Actividades planificadas</span></div>
|
||||
<div className="kpi"><span className="n">{tot.hechas} <small style={{ fontSize: 14 }}>({pct(tot.hechas, tot.plan)})</small></span><span className="l">Completadas</span></div>
|
||||
<div className="kpi"><span className={`n${tot.vencidas ? " pierde" : ""}`}>{tot.vencidas}</span><span className="l">Vencidas (abiertas con fecha ya pasada)</span></div>
|
||||
<div className="kpi"><span className="n">{tot.abiertas}</span><span className="l">Oportunidades abiertas (ventas y renovaciones)</span></div>
|
||||
<div className="kpi"><span className={`n${tot.sinProxima ? " pierde" : ""}`}>{tot.sinProxima}</span><span className="l">Sin próxima actividad registrada</span></div>
|
||||
<div className="kpi"><span className="n">{pct(tot.actualizadas7, tot.abiertas)}</span><span className="l">Actualizadas en los últimos 7 días</span></div>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Actividades {vista === "semana" ? "de la semana" : "del mes"} por ejecutivo</h3>
|
||||
<table className="cta-tabla">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th>
|
||||
{vista === "semana" && diasLab.map((d) => <th key={d} className="num">{diaCorto(d)}</th>)}
|
||||
<th className="num">Planificadas</th><th className="num">Completadas</th><th className="num">Cumplimiento</th><th className="num">Vencidas</th>
|
||||
<th className="num" title="Actividades completadas con Gerencia Comercial marcada">GC participó</th><th className="num" title="Actividades abiertas con Gerencia Comercial marcada">GC participará</th><th className="num" title="De las actividades con Gerencia">Presenciales</th><th className="num" title="Visitas virtuales + llamadas">Virtuales</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{nombres.map((n) => {
|
||||
const L = por[n];
|
||||
return (
|
||||
<tr key={n}>
|
||||
<td>{n}</td>
|
||||
{vista === "semana" && diasLab.map((d) => <td key={d} className="num">{L.porDia[d] || "·"}</td>)}
|
||||
<td className="num">{L.plan}</td><td className="num">{L.hechas}</td><td className="num">{pct(L.hechas, L.plan)}</td>
|
||||
<td className={`num${L.vencidas ? " venc" : ""}`}>{L.vencidas}</td>
|
||||
<td className="num">{L.gcParticipo || "·"}</td><td className="num">{L.gcParticipara || "·"}</td><td className="num">{L.gcPresencial || "·"}</td><td className="num">{L.gcVirtual || "·"}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
<tr>
|
||||
<td><strong>Equipo</strong></td>
|
||||
{vista === "semana" && diasLab.map((d) => <td key={d} className="num"><strong>{tot.porDia[d] || "·"}</strong></td>)}
|
||||
<td className="num"><strong>{tot.plan}</strong></td><td className="num"><strong>{tot.hechas}</strong></td><td className="num"><strong>{pct(tot.hechas, tot.plan)}</strong></td><td className="num"><strong>{tot.vencidas}</strong></td>
|
||||
<td className="num"><strong>{tot.gcParticipo || "·"}</strong></td><td className="num"><strong>{tot.gcParticipara || "·"}</strong></td><td className="num"><strong>{tot.gcPresencial || "·"}</strong></td><td className="num"><strong>{tot.gcVirtual || "·"}</strong></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="panel">
|
||||
<h3>Salud de la tubería al día de hoy ({fecha(hoy)})</h3>
|
||||
<p className="hint">
|
||||
Foto de hoy, no del periodo elegido. «Actualizada» = la oportunidad tuvo algún cambio en los últimos 7 días (indicio: también cuenta un cambio de un flujo automático).
|
||||
«Sin próxima actividad» = ninguna actividad abierta con fecha de hoy en adelante.
|
||||
</p>
|
||||
<table className="cta-tabla">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Ejecutivo</th><th className="num">Abiertas</th><th className="num">Actualizadas 7 días</th><th className="num">Cierre vencido</th>
|
||||
<th className="num">Estancadas</th><th className="num">Sin próxima actividad</th><th className="num">Sin plan de cierre</th><th className="num">Días activo en la app</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{nombres.map((n) => {
|
||||
const L = por[n];
|
||||
return (
|
||||
<tr key={n}>
|
||||
<td>{n}</td><td className="num">{L.abiertas}</td><td className="num">{L.actualizadas7} ({pct(L.actualizadas7, L.abiertas)})</td>
|
||||
<td className="num">{L.cierreVencido}</td><td className="num">{L.estancadas}</td><td className="num">{L.sinProxima}</td><td className="num">{L.sinPlan}</td>
|
||||
<td className="num">{uso[emailDe[n]] || 0}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
<tr>
|
||||
<td><strong>Equipo</strong></td><td className="num"><strong>{tot.abiertas}</strong></td><td className="num"><strong>{tot.actualizadas7} ({pct(tot.actualizadas7, tot.abiertas)})</strong></td>
|
||||
<td className="num"><strong>{tot.cierreVencido}</strong></td><td className="num"><strong>{tot.estancadas}</strong></td><td className="num"><strong>{tot.sinProxima}</strong></td><td className="num"><strong>{tot.sinPlan}</strong></td><td />
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{vista === "mes" && (
|
||||
<div className="panel">
|
||||
<h3>Resultados del mes y cobertura de la meta</h3>
|
||||
<p className="hint">Ventas y renovaciones se muestran por separado (no se suman: la meta excluye renovaciones). Cobertura = (ventas logradas + forecast de lo que cierra en el mes) ÷ meta individual.</p>
|
||||
<table className="cta-tabla">
|
||||
<thead>
|
||||
<tr><th>Ejecutivo</th><th className="num">Ventas logradas</th><th className="num">Renovaciones logradas</th><th className="num">Perdidas (ventas)</th><th className="num">Perdidas (renov.)</th><th className="num">Forecast del mes</th><th className="num">Meta</th><th className="num">Cobertura</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{resultados.map((r) => (
|
||||
<tr key={r.nombre}>
|
||||
<td>{r.nombre}</td><td className="num">{money(r.gv)} ({r.gvN})</td><td className="num">{money(r.gr)} ({r.grN})</td>
|
||||
<td className="num">{money(r.pv)} ({r.pvN})</td><td className="num">{r.pr}</td><td className="num">{money(r.fcMes)}</td>
|
||||
<td className="num">{r.meta ? money(r.meta) : "sin meta"}</td><td className={`num${r.cobertura != null && r.cobertura < 100 ? " venc" : ""}`}>{r.cobertura != null ? `${r.cobertura}%` : "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="panel">
|
||||
<h3>Para conversar con cada ejecutivo ({casos.length} de mayor valor)</h3>
|
||||
<p className="hint">Oportunidades abiertas con el cierre vencido o sin próxima actividad registrada. Desde aquí se agenda la actividad, que queda a nombre del ejecutivo.</p>
|
||||
<table className="cta-tabla">
|
||||
<thead><tr><th>Ejecutivo</th><th>Cliente / oportunidad</th><th>Motivo</th><th className="num">MRR est.</th><th>Cierre est.</th><th>Agendar</th></tr></thead>
|
||||
<tbody>
|
||||
{casos.map((c) => (
|
||||
<tr key={c.id}>
|
||||
<td>{c.owner}</td>
|
||||
<td><a className="opp" href={`${DYN}${c.id}`} target="_blank" rel="noopener">{c.cliente || c.nombre}</a>{c.cliente && <span className="sub">{c.nombre}</span>}</td>
|
||||
<td>{c.motivos.join(" · ")}</td><td className="num">{money(c.valor)}</td><td>{c.cierre ? fecha(c.cierre) : "—"}</td>
|
||||
<td><AgendarBoton opp={{ id: c.id, name: c.nombre, cliente: c.cliente, forecast: c.forecast }} /></td>
|
||||
</tr>
|
||||
))}
|
||||
{!casos.length && <tr><td colSpan={6}>Sin casos: todas las oportunidades abiertas tienen próxima actividad y cierre vigente.</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</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 |
74
app/layout.js
Normal file
74
app/layout.js
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import "./globals.css";
|
||||
import { auth, signIn, signOut } from "./lib/auth";
|
||||
import AppShell from "./components/AppShell";
|
||||
import { esAsistente } from "./lib/authz";
|
||||
|
||||
export const metadata = {
|
||||
title: "Informe Comercial ALFA+",
|
||||
description: "Analítica comercial en vivo sobre Dynamics 365",
|
||||
};
|
||||
|
||||
// Menú por TAREA (decidido con Marco el 2026-11-07, tras la revisión de usabilidad): qué hago hoy, mi semana, mi
|
||||
// cierre, mi cartera, resultados y, aparte, el análisis del equipo. Las páginas conservan su ruta; las que forman una
|
||||
// sección con pestañas (Cierres, Resultados, Semana: ver lib/secciones.js) se marcan activas con `alias`.
|
||||
// `colapsado`: para quien no es gerente, ese grupo aparece plegado (no se oculta ni se bloquea la ruta).
|
||||
const PAGES = [
|
||||
{ href: "/plan", label: "Plan del Día", ico: "☀", grupo: "Hoy", built: true },
|
||||
{ href: "/", label: "Calendario", ico: "🗓", grupo: "Hoy", built: true },
|
||||
|
||||
{ href: "/equipo", label: "Equipo", ico: "👥", grupo: "Equipo", built: true, soloGerente: true },
|
||||
|
||||
{ href: "/actividades", label: "Plan de Actividades", ico: "✓", grupo: "Semana y mes", built: true },
|
||||
{ href: "/agendador", label: "Agendador", ico: "📅", grupo: "Semana y mes", built: true },
|
||||
|
||||
{ href: "/prevision", label: "Previsión y Tubería", ico: "◎", grupo: "Cierre", built: true, alias: ["/tuberia", "/renovaciones/prevision", "/renovaciones/tuberia"] },
|
||||
{ href: "/resumen", label: "Ventas del mes", ico: "▣", grupo: "Cierre", built: true },
|
||||
|
||||
{ href: "/cuentas", label: "Cuentas", ico: "🏢", grupo: "Cartera", built: true, alias: ["/cuentas/ficha"] },
|
||||
|
||||
{ href: "/ganadas", label: "Ganadas", ico: "▲", grupo: "Resultados", built: true, alias: ["/renovaciones/logradas"] },
|
||||
{ href: "/perdemos", label: "Perdidas", ico: "▼", grupo: "Resultados", built: true, alias: ["/renovaciones/perdidas"] },
|
||||
|
||||
{ href: "/tendencia", label: "Tendencia", ico: "📈", grupo: "Análisis del equipo", built: true, colapsado: true },
|
||||
{ href: "/nuevas", label: "Oportunidades nuevas por mes", ico: "◔", grupo: "Análisis del equipo", built: true, colapsado: true },
|
||||
{ href: "/participacion", label: "Participación de Gerencia", ico: "👥", grupo: "Análisis del equipo", built: true, colapsado: true },
|
||||
{ href: "/detalle", label: "Detalle (exportar)", ico: "☰", grupo: "Análisis del equipo", built: true, colapsado: 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, esAsistente: esAsistente(session.email) } : null}
|
||||
onSignIn={handleSignIn}
|
||||
onSignOut={handleSignOut}
|
||||
generatedAt={generatedAt}
|
||||
>
|
||||
{children}
|
||||
</AppShell>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
58
app/lib/actividadAcciones.js
Normal file
58
app/lib/actividadAcciones.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
import db from "./db";
|
||||
|
||||
// Bitácora de cada acción sobre una actividad hecha desde la app (completar, reprogramar, cancelar).
|
||||
// Sirve para (1) «Deshacer» (guarda el estado previo), (2) diagnosticar un fallo sin tener que adivinar y
|
||||
// (3) medir adopción. Se crea aquí (IF NOT EXISTS), igual que agendador_lote.
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS actividad_accion (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
creado_en TEXT NOT NULL,
|
||||
actor_email TEXT NOT NULL,
|
||||
owner_id TEXT,
|
||||
owner_name TEXT,
|
||||
tipo TEXT NOT NULL,
|
||||
activity_id TEXT NOT NULL,
|
||||
accion TEXT NOT NULL,
|
||||
resultado TEXT NOT NULL,
|
||||
error TEXT,
|
||||
previo TEXT,
|
||||
nuevo TEXT,
|
||||
canal TEXT,
|
||||
deshecho_en TEXT,
|
||||
deshecho_por TEXT
|
||||
);
|
||||
`);
|
||||
|
||||
export function registrarAccion({ actor, ownerId, ownerName, tipo, activityId, accion, resultado, error, previo, nuevo, canal }) {
|
||||
const info = db
|
||||
.prepare(
|
||||
`INSERT INTO actividad_accion
|
||||
(creado_en, actor_email, owner_id, owner_name, tipo, activity_id, accion, resultado, error, previo, nuevo, canal)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.run(
|
||||
new Date().toISOString(),
|
||||
actor,
|
||||
ownerId || null,
|
||||
ownerName || null,
|
||||
tipo,
|
||||
activityId,
|
||||
accion,
|
||||
resultado,
|
||||
error ? String(error).slice(0, 500) : null,
|
||||
previo ? JSON.stringify(previo) : null,
|
||||
nuevo ? JSON.stringify(nuevo) : null,
|
||||
canal || "web"
|
||||
);
|
||||
return Number(info.lastInsertRowid);
|
||||
}
|
||||
|
||||
export function getAccion(id) {
|
||||
const r = db.prepare("SELECT * FROM actividad_accion WHERE id = ?").get(id);
|
||||
if (!r) return null;
|
||||
return { ...r, previo: r.previo ? JSON.parse(r.previo) : null, nuevo: r.nuevo ? JSON.parse(r.nuevo) : null };
|
||||
}
|
||||
|
||||
export function marcarAccionDeshecha(id, por) {
|
||||
db.prepare("UPDATE actividad_accion SET deshecho_en = ?, deshecho_por = ? WHERE id = ?").run(new Date().toISOString(), por, id);
|
||||
}
|
||||
298
app/lib/actividadesServer.js
Normal file
298
app/lib/actividadesServer.js
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
// Gestión de UNA actividad (completar, reprogramar, cancelar, deshacer) — solo servidor. Todo con el token
|
||||
// del usuario conectado (derechos del propio usuario) y SIN caché: se valida con el estado de este momento.
|
||||
// Diseño y decisiones: Proyectos/Análisis e Informes/Analitica de CRM/egm/concepts_brief.md
|
||||
import { dvFresh, dvWrite, odataString } from "./dataverse";
|
||||
import { ENTIDAD_TIPO, aUtc, minAHora, horaAMin, localDeIso, AGENDADOR } from "./agendador";
|
||||
import { GC, parseCodigos, formatCodigos } from "./participantes";
|
||||
|
||||
// [statecode, statuscode] de cada estado, por tipo (cancelar ya probado el 2026-10-27; completar y reabrir se
|
||||
// prueban en la oportunidad KUAI antes de publicar — ver sesion.md del 2026-11-06).
|
||||
const ESTADOS = {
|
||||
Llamada: { completada: [1, 2], cancelada: [2, 3] },
|
||||
Cita: { completada: [1, 3], cancelada: [2, 4] },
|
||||
Tarea: { completada: [1, 5], cancelada: [2, 6] },
|
||||
};
|
||||
// Citas: statecode 0 (Abierta) y 3 (Programada) cuentan como abiertas.
|
||||
const abierta = (statecode) => statecode === 0 || statecode === 3;
|
||||
|
||||
const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
function selectDe(tipo) {
|
||||
const base = ["activityid", "subject", "statecode", "statuscode", "scheduledstart", "scheduledend", "_ownerid_value", "_regardingobjectid_value", "description", "actualend"];
|
||||
if (tipo === "Cita") base.push("alfa_resultadodelavisita", "location", "alfa_participantes");
|
||||
// Llamada: columna «Participantes» creada en Dynamics el 2026-11-10 (aprobada por Marco; Tarea NO la tiene).
|
||||
if (tipo === "Llamada") base.push("alfa_participantes");
|
||||
if (tipo === "Tarea") base.push("percentcomplete");
|
||||
return base.join(",");
|
||||
}
|
||||
|
||||
// Lee la actividad con datos de este momento. Para citas cuenta los invitados (asistentes requeridos u
|
||||
// opcionales): reprogramar o cancelar una cita con invitados puede mandarles avisos, y eso no se deshace.
|
||||
export async function leerActividad(token, tipo, id) {
|
||||
const ent = ENTIDAD_TIPO[tipo];
|
||||
const NAV_OBJ = { Llamada: "alfa_ObjetivodeActividad_PhoneCall", Cita: "alfa_ObjetivodeActividad_Appointment", Tarea: "alfa_ObjetivodeActividad_Task" }[tipo];
|
||||
const expand = `&$expand=${tipo === "Cita" ? "appointment_activity_parties($select=participationtypemask)," : ""}${NAV_OBJ}($select=alfa_objetivo,alfa_objetivosdeactividadesid)`;
|
||||
const d = await dvFresh(`${ent}(${odataString(id)})?$select=${selectDe(tipo)}${expand}`, token);
|
||||
const invitados = tipo === "Cita" ? (d.appointment_activity_parties || []).filter((p) => p.participationtypemask === 5 || p.participationtypemask === 6).length : 0;
|
||||
return {
|
||||
id: d.activityid,
|
||||
tipo,
|
||||
etag: d["@odata.etag"] || null,
|
||||
asunto: d.subject || "(sin asunto)",
|
||||
statecode: d.statecode,
|
||||
statuscode: d.statuscode,
|
||||
estado: d.statecode === 1 ? "completada" : d.statecode === 2 ? "cancelada" : "abierta",
|
||||
scheduledstart: d.scheduledstart || null,
|
||||
scheduledend: d.scheduledend || null,
|
||||
ownerId: d._ownerid_value || null,
|
||||
owner: d["_ownerid_value@OData.Community.Display.V1.FormattedValue"] || "",
|
||||
referente: d["_regardingobjectid_value@OData.Community.Display.V1.FormattedValue"] || null,
|
||||
// Solo si «Referente a» es una oportunidad (también puede ser cuenta o caso): ahí se suma la participación.
|
||||
oppId: d["_regardingobjectid_value@Microsoft.Dynamics.CRM.lookuplogicalname"] === "opportunity" ? d._regardingobjectid_value : null,
|
||||
participantes: parseCodigos(d.alfa_participantes),
|
||||
description: d.description ?? null,
|
||||
resultadoVisita: d.alfa_resultadodelavisita ?? null,
|
||||
actualend: d.actualend || null,
|
||||
percentcomplete: d.percentcomplete ?? null,
|
||||
invitados,
|
||||
objetivo: d[NAV_OBJ]?.alfa_objetivo ? String(d[NAV_OBJ].alfa_objetivo).trim() : null,
|
||||
objetivoId: d[NAV_OBJ]?.alfa_objetivosdeactividadesid || null,
|
||||
lugar: d.location ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
// Propiedad de navegación del objetivo de cada tipo (para escribirlo con @odata.bind).
|
||||
const NAV_OBJETIVO = { Llamada: "alfa_ObjetivodeActividad_PhoneCall", Cita: "alfa_ObjetivodeActividad_Appointment", Tarea: "alfa_ObjetivodeActividad_Task" };
|
||||
|
||||
// Nota ya guardada, como TEXTO plano para mostrarla (sin HTML, sin la línea técnica de origen). Cita → «Resultado de la
|
||||
// visita» (nunca la descripción: es la invitación al cliente); llamada y tarea → descripción.
|
||||
export function notaLegible(act) {
|
||||
let t = act.tipo === "Cita" ? act.resultadoVisita : act.description;
|
||||
if (!t) return "";
|
||||
t = String(t)
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<\/p>/gi, "\n")
|
||||
.replace(/<[^>]*>/g, "")
|
||||
.replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
|
||||
return t
|
||||
.split("\n")
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !/^Creada (desde el informe comercial|por el agendador de actividades)/i.test(l))
|
||||
.join("\n")
|
||||
.slice(0, 800);
|
||||
}
|
||||
|
||||
// Editar una actividad ABIERTA sin completarla: objetivo, duración (llamada/visita), nota previa y participantes (solo
|
||||
// visitas: llamadas y tareas no tienen el campo). NO toca asunto, descripción ni invitados. Escribe con If-Match.
|
||||
// Devuelve null si no había nada que cambiar; si no, { previo, nuevo } para poder deshacer.
|
||||
export async function editarActividad(token, act, { objetivoId, duracionMin, nota, participantes }) {
|
||||
const url = `${ENTIDAD_TIPO[act.tipo]}(${odataString(act.id)})`;
|
||||
const campos = {};
|
||||
const previo = {};
|
||||
const nuevo = {};
|
||||
if (objetivoId && objetivoId !== act.objetivoId) {
|
||||
campos[`${NAV_OBJETIVO[act.tipo]}@odata.bind`] = `/alfa_objetivosdeactividadeses(${objetivoId})`;
|
||||
previo.objetivoId = act.objetivoId;
|
||||
nuevo.objetivoId = objetivoId;
|
||||
}
|
||||
if (duracionMin && act.tipo !== "Tarea" && act.scheduledstart) {
|
||||
const fin = new Date(new Date(act.scheduledstart).getTime() + duracionMin * 60000).toISOString();
|
||||
if (!act.scheduledend || new Date(act.scheduledend).getTime() !== new Date(fin).getTime()) {
|
||||
campos.scheduledend = fin;
|
||||
previo.scheduledend = act.scheduledend;
|
||||
nuevo.scheduledend = fin;
|
||||
}
|
||||
}
|
||||
const campoNota = camposDeNota(act, nota);
|
||||
if (Object.keys(campoNota).length) {
|
||||
Object.assign(campos, campoNota);
|
||||
if (act.tipo === "Cita") previo.resultadoVisita = act.resultadoVisita ?? null;
|
||||
else previo.description = act.description ?? null;
|
||||
nuevo.nota = true;
|
||||
}
|
||||
if ((act.tipo === "Cita" || act.tipo === "Llamada") && Array.isArray(participantes) && formatCodigos(participantes) !== formatCodigos(act.participantes)) {
|
||||
campos.alfa_participantes = participantes.length ? formatCodigos(participantes) : null;
|
||||
previo.participantes = act.participantes;
|
||||
nuevo.participantes = participantes;
|
||||
}
|
||||
if (!Object.keys(campos).length) return null;
|
||||
await dvWrite("PATCH", url, token, campos, act.etag ? { "If-Match": act.etag } : {});
|
||||
return { previo, nuevo };
|
||||
}
|
||||
|
||||
// Deshace una edición: devuelve cada campo cambiado a su valor previo (la actividad debe seguir abierta).
|
||||
export async function deshacerEdicion(token, tipo, id, previo, nuevo) {
|
||||
const act = await leerActividad(token, tipo, id);
|
||||
if (!abierta(act.statecode)) return "CAMBIO";
|
||||
const campos = {};
|
||||
if ("objetivoId" in previo) campos[`${NAV_OBJETIVO[tipo]}@odata.bind`] = previo.objetivoId ? `/alfa_objetivosdeactividadeses(${previo.objetivoId})` : null;
|
||||
if ("scheduledend" in previo) campos.scheduledend = previo.scheduledend;
|
||||
if ("resultadoVisita" in previo) campos.alfa_resultadodelavisita = previo.resultadoVisita;
|
||||
if ("description" in previo) campos.description = previo.description;
|
||||
if ("participantes" in previo) campos.alfa_participantes = previo.participantes.length ? formatCodigos(previo.participantes) : null;
|
||||
if (!Object.keys(campos).length) return "ok";
|
||||
await dvWrite("PATCH", `${ENTIDAD_TIPO[tipo]}(${odataString(id)})`, token, campos);
|
||||
return "ok";
|
||||
}
|
||||
|
||||
// Dónde va la nota de cada tipo. Cita → «Resultado de la visita» (texto enriquecido, HTML): NUNCA la
|
||||
// descripción, que lleva la invitación de Teams/Outlook que se envía al contacto. Llamada y tarea → descripción.
|
||||
// Siempre se ANTEPONE: lo que el ejecutivo ya había escrito no se pierde.
|
||||
function camposDeNota(act, nota) {
|
||||
const t = String(nota || "").trim();
|
||||
if (!t) return {};
|
||||
if (act.tipo === "Cita") {
|
||||
const previo = act.resultadoVisita || "";
|
||||
return { alfa_resultadodelavisita: `<p>${esc(t).replace(/\n/g, "<br>")}</p>${previo}` };
|
||||
}
|
||||
return { description: act.description ? `${t}\n\n${act.description}` : t };
|
||||
}
|
||||
|
||||
const sinInvitados = (act) => (act.tipo === "Cita" && act.invitados > 0 ? "CON_INVITADOS" : null);
|
||||
|
||||
// Valida que la actividad se pueda tocar. Devuelve un código de error o null.
|
||||
export function problemaPara(act, accion) {
|
||||
if (!abierta(act.statecode)) return "CERRADA";
|
||||
if ((accion === "reprogramar" || accion === "cancelar") && sinInvitados(act)) return "CON_INVITADOS";
|
||||
return null;
|
||||
}
|
||||
|
||||
// Foto de lo que se va a cambiar, para poder deshacerlo.
|
||||
const fotoDe = (act) => ({
|
||||
statecode: act.statecode,
|
||||
statuscode: act.statuscode,
|
||||
scheduledstart: act.scheduledstart,
|
||||
scheduledend: act.scheduledend,
|
||||
description: act.description,
|
||||
resultadoVisita: act.resultadoVisita,
|
||||
actualend: act.actualend,
|
||||
percentcomplete: act.percentcomplete,
|
||||
participantes: act.participantes,
|
||||
});
|
||||
|
||||
async function cerrar(token, act, estado, nota, extra = {}) {
|
||||
const ent = ENTIDAD_TIPO[act.tipo];
|
||||
const url = `${ent}(${odataString(act.id)})`;
|
||||
// 1) Los datos (nota, fecha real, avance) se escriben con la actividad todavía abierta y con `If-Match`:
|
||||
// si el ejecutivo la cambió en Dynamics mientras tanto, falla (412) y no se pisa nada.
|
||||
const campos = { ...camposDeNota(act, nota), ...extra };
|
||||
if (Object.keys(campos).length) {
|
||||
await dvWrite("PATCH", url, token, campos, act.etag ? { "If-Match": act.etag } : {});
|
||||
}
|
||||
// 2) El cambio de estado va aparte.
|
||||
const [statecode, statuscode] = ESTADOS[act.tipo][estado];
|
||||
await dvWrite("PATCH", url, token, { statecode, statuscode });
|
||||
}
|
||||
|
||||
export async function completarActividad(token, act, nota, participantes = [], actualend = null) {
|
||||
const extra = { actualend: actualend || new Date().toISOString() };
|
||||
if (act.tipo === "Tarea") extra.percentcomplete = 100;
|
||||
// Una actividad cerrada es de solo lectura en Dynamics: los participantes de la cita se escriben ANTES
|
||||
// de cerrarla (junto con la nota), nunca después.
|
||||
if ((act.tipo === "Cita" || act.tipo === "Llamada") && participantes.length) extra.alfa_participantes = formatCodigos(participantes);
|
||||
await cerrar(token, act, "completada", nota, extra);
|
||||
return { statecode: 1, statuscode: ESTADOS[act.tipo].completada[1] };
|
||||
}
|
||||
|
||||
export async function cancelarActividad(token, act, nota) {
|
||||
await cerrar(token, act, "cancelada", nota);
|
||||
return { statecode: 2, statuscode: ESTADOS[act.tipo].cancelada[1] };
|
||||
}
|
||||
|
||||
// Nueva fecha. Llamadas y citas conservan su duración (si no tienen, la duración estándar de AGENDADOR: llamada 10 min, visita 60); las tareas vencen a las 16:00.
|
||||
export async function reprogramarActividad(token, act, dia, hora) {
|
||||
const ent = ENTIDAD_TIPO[act.tipo];
|
||||
let inicio;
|
||||
let fin;
|
||||
if (act.tipo === "Tarea") {
|
||||
inicio = aUtc(dia, minAHora(AGENDADOR.horaTarea));
|
||||
fin = inicio;
|
||||
} else {
|
||||
let dur = AGENDADOR.duracion[act.tipo];
|
||||
if (act.scheduledstart && act.scheduledend) {
|
||||
const m = Math.round((new Date(act.scheduledend) - new Date(act.scheduledstart)) / 60000);
|
||||
if (m > 0 && m <= 480) dur = m;
|
||||
}
|
||||
inicio = aUtc(dia, hora);
|
||||
fin = aUtc(dia, minAHora(horaAMin(hora) + dur));
|
||||
}
|
||||
await dvWrite("PATCH", `${ent}(${odataString(act.id)})`, token, { scheduledstart: inicio, scheduledend: fin }, act.etag ? { "If-Match": act.etag } : {});
|
||||
return { scheduledstart: inicio, scheduledend: fin };
|
||||
}
|
||||
|
||||
// ---- Participación en la oportunidad -------------------------------------------------------------------
|
||||
// Gerencia Comercial → Sí/No `alfa_participaciondegv` (alimenta la puntuación); los demás roles → el campo
|
||||
// múltiple `alfa_participantes`. Solo SUMA (nunca quita ni baja un Sí a No) y se registra lo anterior para
|
||||
// poder deshacerlo.
|
||||
export async function leerParticipacionOpp(token, oppId) {
|
||||
const d = await dvFresh(`opportunities(${odataString(oppId)})?$select=alfa_participaciondegv,alfa_participantes,statecode`, token);
|
||||
return { id: oppId, etag: d["@odata.etag"] || null, gv: d.alfa_participaciondegv === true, participantes: parseCodigos(d.alfa_participantes), abierta: d.statecode === 0 };
|
||||
}
|
||||
|
||||
export async function sumarParticipacionOpp(token, oppId, codigos) {
|
||||
const o = await leerParticipacionOpp(token, oppId);
|
||||
// Gerencia Comercial va SOLO en el Sí/No de la oportunidad (decisión de Marco); el campo múltiple recibe
|
||||
// los demás roles.
|
||||
const union = parseCodigos(formatCodigos([...o.participantes, ...codigos.filter((c) => c !== GC)]));
|
||||
const cuerpo = {};
|
||||
if (formatCodigos(union) !== formatCodigos(o.participantes)) cuerpo.alfa_participantes = formatCodigos(union);
|
||||
if (codigos.includes(GC) && !o.gv) cuerpo.alfa_participaciondegv = true;
|
||||
if (!Object.keys(cuerpo).length) return { cambio: false, yaTenia: { gv: o.gv, participantes: o.participantes } };
|
||||
await dvWrite("PATCH", `opportunities(${odataString(oppId)})`, token, cuerpo, o.etag ? { "If-Match": o.etag } : {});
|
||||
return {
|
||||
cambio: true,
|
||||
previo: { id: oppId, gv: o.gv, participantes: o.participantes },
|
||||
nuevo: { id: oppId, gv: cuerpo.alfa_participaciondegv ?? o.gv, participantes: union },
|
||||
};
|
||||
}
|
||||
|
||||
// Devuelve la oportunidad a como estaba, tocando SOLO lo que la acción cambió.
|
||||
export async function restaurarParticipacionOpp(token, previo, nuevo) {
|
||||
const cuerpo = {};
|
||||
if (previo.gv !== nuevo.gv) cuerpo.alfa_participaciondegv = previo.gv;
|
||||
if (formatCodigos(previo.participantes) !== formatCodigos(nuevo.participantes)) cuerpo.alfa_participantes = previo.participantes.length ? formatCodigos(previo.participantes) : null;
|
||||
if (!Object.keys(cuerpo).length) return;
|
||||
await dvWrite("PATCH", `opportunities(${odataString(previo.id)})`, token, cuerpo);
|
||||
}
|
||||
|
||||
// «Deshacer»: restaura la foto previa. Solo si la actividad sigue como la dejó la acción (si alguien la tocó
|
||||
// después, no se pisa).
|
||||
export async function deshacerAccion(token, tipo, id, accion, previo, nuevo) {
|
||||
const act = await leerActividad(token, tipo, id);
|
||||
const ent = ENTIDAD_TIPO[tipo];
|
||||
const url = `${ent}(${odataString(id)})`;
|
||||
if (accion === "reprogramar") {
|
||||
// Se comparan como instantes: Dynamics devuelve «…:00Z» y nosotros guardamos «…:00.000Z».
|
||||
const mismo = act.scheduledstart && nuevo.scheduledstart && new Date(act.scheduledstart).getTime() === new Date(nuevo.scheduledstart).getTime();
|
||||
if (!abierta(act.statecode) || !mismo) return "CAMBIO";
|
||||
await dvWrite("PATCH", url, token, { scheduledstart: previo.scheduledstart, scheduledend: previo.scheduledend });
|
||||
return "ok";
|
||||
}
|
||||
// completar / cancelar: reabre (vuelve al estado previo) y devuelve la nota y la fecha real a como estaban.
|
||||
if (act.statecode !== nuevo.statecode) return "CAMBIO";
|
||||
await dvWrite("PATCH", url, token, { statecode: previo.statecode, statuscode: previo.statuscode });
|
||||
const campos = { actualend: previo.actualend ?? null };
|
||||
if (tipo === "Cita") {
|
||||
campos.alfa_resultadodelavisita = previo.resultadoVisita ?? null;
|
||||
} else campos.description = previo.description ?? null;
|
||||
if (nuevo.escribioParticipantes && (tipo === "Cita" || tipo === "Llamada")) campos.alfa_participantes = previo.participantes?.length ? formatCodigos(previo.participantes) : null;
|
||||
if (tipo === "Tarea") campos.percentcomplete = previo.percentcomplete ?? 0;
|
||||
let resultado = "ok";
|
||||
try {
|
||||
await dvWrite("PATCH", url, token, campos);
|
||||
} catch {
|
||||
// La actividad ya quedó abierta; si no se pudo devolver la nota, no se falla el deshacer entero.
|
||||
resultado = "ok_sin_nota";
|
||||
}
|
||||
// La participación que la acción sumó a la oportunidad también se devuelve.
|
||||
if (previo.opp && nuevo.opp) {
|
||||
try {
|
||||
await restaurarParticipacionOpp(token, previo.opp, nuevo.opp);
|
||||
} catch {
|
||||
resultado = "ok_sin_opp";
|
||||
}
|
||||
}
|
||||
return resultado;
|
||||
}
|
||||
|
||||
export { fotoDe, localDeIso };
|
||||
182
app/lib/agendaDia.js
Normal file
182
app/lib/agendaDia.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
// Vista cronológica del Plan del Día y del Plan de Actividades (rediseño 2026-11-13, solo pantalla; el PDF sigue por objetivo).
|
||||
// Funciones PURAS: reagrupan lo que ya arma lib/plan.js (armarPlan / armarPlanPeriodo) en una lista plana de actividades,
|
||||
// una por fila, ordenada por hora, y calculan cruces de horario y huecos libres. No tocan reglas de negocio ni Dynamics.
|
||||
import { AGENDADOR, localDeIso, minAHora } from "./agendador";
|
||||
import { diaDe, esHabil } from "./plan";
|
||||
import { gcDe } from "./gerencia";
|
||||
import { etiquetasGV } from "./planDia";
|
||||
|
||||
export const ROTULO_TIPO = { Llamada: "Llamada", Cita: "Visita", Tarea: "Tarea" };
|
||||
export const ICONO_TIPO = { Llamada: "📞", Cita: "🤝", Tarea: "☑" };
|
||||
const ORDEN_TIPO = { Llamada: 0, Cita: 1, Tarea: 2 };
|
||||
|
||||
// Instante con que se muestra la actividad: llamada/visita = inicio; tarea = vencimiento (igual que AccionesFila).
|
||||
const instante = (a) => (a.tipo === "Tarea" ? a.scheduledend || a.scheduledstart : a.scheduledstart || a.scheduledend);
|
||||
|
||||
// Duración en minutos de una llamada o visita: la real (scheduledend - scheduledstart) si existe; si no, la del agendador.
|
||||
function duracionDe(a) {
|
||||
if (a.tipo === "Tarea") return null;
|
||||
if (a.scheduledstart && a.scheduledend) {
|
||||
const d = Math.round((Date.parse(a.scheduledend) - Date.parse(a.scheduledstart)) / 60000);
|
||||
if (d > 0) return d;
|
||||
}
|
||||
return AGENDADOR.duracion[a.tipo] ?? 10;
|
||||
}
|
||||
|
||||
// Una entrada por actividad de cada fila del plan. `secciones`: salida de armarPlan / armarPlanPeriodo.
|
||||
// La sección (color, chip) es la de la FILA donde hoy aparece la actividad (la que ya decide lib/plan.js), así chips,
|
||||
// barra del PDF y MRR por sección cuadran. `porHora`: una actividad abierta de HOY cuya hora ya pasó cuenta como vencida
|
||||
// (Plan del Día); sin ella, solo vencen las de días anteriores a hoy (criterio del Plan de Actividades y de su filtro ?venc=1).
|
||||
export function listaPlana(secciones, { hoy, ahoraMin = 0, porHora = false }) {
|
||||
const out = [];
|
||||
for (const s of secciones) {
|
||||
for (const r of s.filas) {
|
||||
const filaGC = r.acts.some((a) => gcDe(a));
|
||||
for (const a of r.acts) {
|
||||
const iso = instante(a);
|
||||
const min = iso ? localDeIso(iso).min : null;
|
||||
const dia = diaDe(a);
|
||||
const abierta = a.estado !== "completada";
|
||||
const vencida = abierta && !!dia && (dia < hoy || (porHora && dia === hoy && min != null && min < ahoraMin));
|
||||
out.push({
|
||||
id: a.id,
|
||||
fila: r.key,
|
||||
sec: s.key,
|
||||
secTitulo: s.titulo,
|
||||
owner: r.owner,
|
||||
dia,
|
||||
min,
|
||||
dur: duracionDe(a),
|
||||
tipo: a.tipo,
|
||||
esTarea: a.tipo === "Tarea",
|
||||
completada: a.estado === "completada",
|
||||
vencida,
|
||||
objetivo: a.objetivo || "(sin objetivo)",
|
||||
valor: r.opp.valor ?? null,
|
||||
opp: r.opp,
|
||||
a,
|
||||
gv: etiquetasGV([a]),
|
||||
esGC: !!gcDe(a),
|
||||
filaGC,
|
||||
filaVencidas: r.vencidas || 0,
|
||||
cruce: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort(comparar);
|
||||
}
|
||||
|
||||
// Orden: día, tareas al final de su día, hora, tipo (llamada antes que visita), ejecutivo.
|
||||
function comparar(x, y) {
|
||||
return (
|
||||
String(x.dia).localeCompare(String(y.dia)) ||
|
||||
Number(x.esTarea) - Number(y.esTarea) ||
|
||||
(x.min ?? 1e9) - (y.min ?? 1e9) ||
|
||||
ORDEN_TIPO[x.tipo] - ORDEN_TIPO[y.tipo] ||
|
||||
x.owner.localeCompare(y.owner)
|
||||
);
|
||||
}
|
||||
|
||||
// Marca las llamadas/visitas ABIERTAS de un mismo ejecutivo y día cuyos horarios se solapan: it.cruce = «visita 09:00» (+N).
|
||||
// Muta y devuelve la misma lista.
|
||||
export function marcarCruces(items) {
|
||||
const grupos = new Map();
|
||||
for (const it of items) {
|
||||
if (it.esTarea || it.completada || it.min == null || !it.dur) continue;
|
||||
const k = `${it.owner}|${it.dia}`;
|
||||
if (!grupos.has(k)) grupos.set(k, []);
|
||||
grupos.get(k).push(it);
|
||||
}
|
||||
for (const g of grupos.values()) {
|
||||
for (const x of g) {
|
||||
const otros = g.filter((y) => y !== x && x.min < y.min + y.dur && y.min < x.min + x.dur);
|
||||
if (!otros.length) continue;
|
||||
const o = otros[0];
|
||||
x.cruce = `${ROTULO_TIPO[o.tipo].toLowerCase()} de ${minAHora(o.min)}${otros.length > 1 ? ` (+${otros.length - 1})` : ""}`;
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Huecos libres de ≥ 60 min dentro de las franjas del agendador, entre las llamadas/visitas con hora del día `dia`
|
||||
// (de UN ejecutivo). Solo de hoy en adelante, en día hábil; en hoy, desde la hora actual (redondeada a 10 min).
|
||||
// Devuelve [{ dia, desde, hasta, minutos, visitas, llamadas }].
|
||||
export function huecosLibres(items, dia, hoy, ahoraMin) {
|
||||
if (!dia || dia < hoy || !esHabil(dia)) return [];
|
||||
const ocupados = items
|
||||
.filter((it) => it.dia === dia && !it.esTarea && it.min != null && it.dur)
|
||||
.map((it) => [it.min, it.min + it.dur])
|
||||
.sort((p, q) => p[0] - q[0]);
|
||||
const out = [];
|
||||
const empuja = (desde, hasta) => {
|
||||
const minutos = hasta - desde;
|
||||
if (minutos >= 60) out.push({ dia, desde, hasta, minutos, visitas: Math.floor(minutos / 60), llamadas: Math.floor(minutos / AGENDADOR.duracion.Llamada) });
|
||||
};
|
||||
for (const [a0, b] of AGENDADOR.franjas) {
|
||||
let cur = dia === hoy ? Math.max(a0, Math.ceil(ahoraMin / 10) * 10) : a0;
|
||||
if (cur >= b) continue;
|
||||
for (const [s, e] of ocupados) {
|
||||
if (e <= cur) continue;
|
||||
if (s >= b) break;
|
||||
if (s > cur) empuja(cur, Math.min(s, b));
|
||||
cur = Math.max(cur, e);
|
||||
if (cur >= b) break;
|
||||
}
|
||||
if (cur < b) empuja(cur, b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Filas visibles de un grupo (ya ordenado): { k: "act", it } | { k: "hueco", h } | { k: "ahora", min } | { k: "tareas" }.
|
||||
// Las llamadas/visitas y los huecos se intercalan por hora; la línea «Ahora» (si se pide) va antes de lo que viene;
|
||||
// las tareas van al final, tras un separador si `conSeparadorTareas`.
|
||||
export function intercalar(items, { huecos = [], ahoraMin = null, conSeparadorTareas = false } = {}) {
|
||||
const conHora = items.filter((it) => !it.esTarea);
|
||||
const tareas = items.filter((it) => it.esTarea);
|
||||
const mezcla = [
|
||||
...conHora.map((it) => ({ clave: it.min ?? 1e9, fila: { k: "act", it } })),
|
||||
...huecos.map((h) => ({ clave: h.desde, fila: { k: "hueco", h } })),
|
||||
];
|
||||
if (ahoraMin != null) mezcla.push({ clave: ahoraMin - 0.5, fila: { k: "ahora", min: ahoraMin } });
|
||||
mezcla.sort((p, q) => p.clave - q.clave);
|
||||
const rows = mezcla.map((m) => m.fila);
|
||||
if (tareas.length) {
|
||||
if (conSeparadorTareas) rows.push({ k: "tareas" });
|
||||
for (const it of tareas) rows.push({ k: "act", it });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Agrupa una lista ya ordenada por `owner` o por `dia`; grupos en orden de clave.
|
||||
export function agrupar(items, por) {
|
||||
const m = new Map();
|
||||
for (const it of items) {
|
||||
const k = it[por];
|
||||
if (!m.has(k)) m.set(k, []);
|
||||
m.get(k).push(it);
|
||||
}
|
||||
return [...m.entries()].sort((p, q) => String(p[0]).localeCompare(String(q[0]))).map(([key, its]) => ({ key, items: its }));
|
||||
}
|
||||
|
||||
// Totales de una lista: actividades, hechas, vencidas y MRR SIN contar dos veces la misma oportunidad/caso/cuenta
|
||||
// (una fila del plan con varias actividades suma su valor una sola vez, igual que los subtotales de lib/plan.js).
|
||||
export function totales(items) {
|
||||
const filas = new Map();
|
||||
let hechas = 0;
|
||||
let vencidas = 0;
|
||||
for (const it of items) {
|
||||
filas.set(it.fila, it.valor || 0);
|
||||
if (it.completada) hechas++;
|
||||
if (it.vencida) vencidas++;
|
||||
}
|
||||
let mrr = 0;
|
||||
for (const v of filas.values()) mrr += v;
|
||||
return { n: items.length, hechas, vencidas, mrr };
|
||||
}
|
||||
|
||||
const DIAS_LARGOS = ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"];
|
||||
// «Lunes 16/11» a partir de «2026-11-16».
|
||||
export const etiquetaDia = (iso) => `${DIAS_LARGOS[new Date(`${iso}T12:00:00Z`).getUTCDay()]} ${iso.slice(8, 10)}/${iso.slice(5, 7)}`;
|
||||
|
||||
export const durTxt = (it) => (it.esTarea ? "tarea" : it.dur ? `${it.dur} min` : "");
|
||||
26
app/lib/agendaVista.js
Normal file
26
app/lib/agendaVista.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Cómo se nombra una actividad en la Agenda, de forma uniforme para todos los tipos. El asunto lo escribe cada
|
||||
// quien a su manera (y cambia según se creó la actividad), así que NO se usa para identificar al cliente.
|
||||
|
||||
// Cliente: la cuenta a la que va ligada la actividad, o el cliente de la oportunidad.
|
||||
export function clienteDe(a) {
|
||||
if (a.referente?.tipo === "account") return a.referente.nombre;
|
||||
return a.oportunidad?.cliente || (a.referente?.tipo === "opportunity" ? null : a.referente?.nombre) || null;
|
||||
}
|
||||
|
||||
// Oportunidad (solo si la actividad va ligada a una).
|
||||
export function oportunidadDe(a) {
|
||||
return a.oportunidad?.nombre || (a.referente?.tipo === "opportunity" ? a.referente.nombre : null);
|
||||
}
|
||||
|
||||
// Texto del tooltip: los mismos datos, en el mismo orden, para llamada, visita y tarea.
|
||||
export function tooltipDe(a, hora) {
|
||||
const f = (a.scheduledstart || a.scheduledend || "").slice(0, 10).split("-").reverse().join("/");
|
||||
return [
|
||||
`${a.tipo === "Cita" ? "Visita" : a.tipo}${hora ? ` · ${hora}` : ""}${f ? ` · ${f}` : ""}`,
|
||||
`Cliente: ${clienteDe(a) || "—"}`,
|
||||
`Oportunidad: ${oportunidadDe(a) || "—"}`,
|
||||
`Objetivo: ${a.objetivo || "—"}`,
|
||||
`Propietario: ${a.owner || "—"}`,
|
||||
`Asunto: ${a.asunto || "—"}`,
|
||||
].join("\n");
|
||||
}
|
||||
333
app/lib/agendador.js
Normal file
333
app/lib/agendador.js
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
// Agendador de actividades — 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";
|
||||
import { addDays, esHabil } from "./plan";
|
||||
|
||||
export const AGENDADOR = {
|
||||
// Ejecutivos con agendador. Empezó como piloto de María (2026-10-27); desde 2026-11-06 va para los 5
|
||||
// ejecutivos de venta (a pedido de Marco, para presentarlo al equipo). Para quitar a alguien, sacar su correo.
|
||||
piloto: [
|
||||
"mirna.obando@alfa.com.ni",
|
||||
"maria.marenco@alfa.com.ni",
|
||||
"denis.urroz@alfa.com.ni",
|
||||
"daybellys.perez@alfa.com.ni",
|
||||
"martha.somarriba@alfa.com.ni",
|
||||
// Marco (administrador): para probar y presentar con sus oportunidades de prueba (EMPRESA ABC).
|
||||
"marco.montenegro@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 (2026-11-11: 10 y 4); el de tareas es un supuesto.
|
||||
topes: { Llamada: 10, Cita: 4, Tarea: 6 },
|
||||
// Horario (hora de Nicaragua, minutos desde las 00:00), de lunes a viernes: 8:30–12:00 y 13:30–17:00 (2026-11-11).
|
||||
// Cuadra: 4 visitas de 60 min + 10 llamadas de 10 min = 340 min de los 420 que tiene el día.
|
||||
franjas: [[510, 720], [810, 1020]],
|
||||
duracion: { Llamada: 10, Cita: 60 }, // minutos (llamada 30 → 10 el 2026-11-11)
|
||||
paso: { Llamada: 10, Cita: 30 }, // las horas de inicio salen cada 10 min (llamadas) o cada 30 min (visitas)
|
||||
// Las tareas no ocupan horario: vencen a las 16:00 del día elegido. Es una hora de vencimiento fija, NO está
|
||||
// ligada al fin de la franja de la tarde (el 2026-11-11 la franja pasó a 17:00 y se dejó en 16:00 a propósito).
|
||||
horaTarea: 960,
|
||||
horizonteDias: 30, // se puede agendar desde hoy hasta hoy + 30 días (2026-11-06)
|
||||
diasVentana: 5, // la propuesta reparte en 5 días hábiles a partir de la fecha elegida
|
||||
};
|
||||
|
||||
// Días hábiles de agendado: los primeros 5 días hábiles desde la fecha elegida (nunca antes de hoy).
|
||||
// Devuelve [] si la fecha pasa del horizonte (hoy + 30 días).
|
||||
export function ventanaDe(fecha, hoy) {
|
||||
const max = addDays(hoy, AGENDADOR.horizonteDias);
|
||||
let d = fecha && fecha > hoy ? fecha : hoy;
|
||||
if (d > max) return [];
|
||||
const out = [];
|
||||
for (let i = 0; i < 40 && out.length < AGENDADOR.diasVentana; i++, d = addDays(d, 1)) if (esHabil(d)) out.push(d);
|
||||
return out;
|
||||
}
|
||||
export const fechaMaxima = (hoy) => addDays(hoy, AGENDADOR.horizonteDias);
|
||||
|
||||
// Prioridad sugerida (variante E, validada por Marco el 2026-11-06 tras compararla con Mirna, Daybellys
|
||||
// y Denis). Reglas explicables, no un puntaje:
|
||||
// Revisar fecha = vencida con forecast ≤40 % (probable fecha desactualizada: se corrige o se cierra)
|
||||
// Alta = forecast ≥80 %, o valor en el tercio superior de SU cartera con forecast ≥50 %
|
||||
// Baja = forecast ≤40 % con valor en el tercio inferior, o cierre a más de 60 días
|
||||
// Media = el resto
|
||||
// Los tercios de valor se miden sobre la cartera completa de ese ejecutivo (no hay montos fijos).
|
||||
export const NIVELES_PRIO = ["Alta", "Media", "Baja", "Revisar fecha"];
|
||||
export function calcularPrioridades(candidatos, hoy) {
|
||||
const vals = candidatos.map((c) => c.valor || 0).sort((a, b) => a - b);
|
||||
const q = (p) => (vals.length ? vals[Math.floor(p * (vals.length - 1))] : 0);
|
||||
const lo = q(1 / 3);
|
||||
const hi = q(2 / 3);
|
||||
const limite60 = addDays(hoy, 60);
|
||||
const out = new Map();
|
||||
for (const c of candidatos) {
|
||||
const pct = c.pct || 0;
|
||||
const v = c.valor || 0;
|
||||
const vencida = !!c.cierre && c.cierre < hoy;
|
||||
const alto = v > 0 && v >= hi;
|
||||
let nivel;
|
||||
const motivos = [];
|
||||
if (vencida && pct <= 40) {
|
||||
nivel = "Revisar fecha";
|
||||
motivos.push("Vencida con forecast bajo");
|
||||
} else if (pct >= 80 || (alto && pct >= 50)) {
|
||||
nivel = "Alta";
|
||||
if (pct >= 80) motivos.push("Etapa avanzada");
|
||||
if (alto && pct >= 50) motivos.push("Valor alto");
|
||||
if (vencida) motivos.push("Cierre vencido");
|
||||
} else if ((pct <= 40 && v <= lo) || (c.cierre && c.cierre > limite60)) {
|
||||
nivel = "Baja";
|
||||
motivos.push(c.cierre && c.cierre > limite60 ? "Cierre lejano" : "Etapa temprana y valor bajo");
|
||||
} else {
|
||||
nivel = "Media";
|
||||
motivos.push(pct >= 50 ? "Etapa intermedia" : "Etapa temprana");
|
||||
if (vencida) motivos.push("Cierre vencido");
|
||||
}
|
||||
out.set(c.id, { prioNivel: nivel, prioRank: NIVELES_PRIO.indexOf(nivel), prioMotivos: motivos.slice(0, 2) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Orden para repartir la agenda: prioridad (Alta primero), luego mayor valor.
|
||||
export const porPrioridadSugerida = (x, y) => (x.prioRank ?? 1) - (y.prioRank ?? 1) || (y.valor || 0) - (x.valor || 0) || (y.pct || 0) - (x.pct || 0);
|
||||
|
||||
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",
|
||||
];
|
||||
|
||||
// Objetivos al crear una actividad a mano (calendario, ficha de cuenta, seguimiento): los del Agendador más
|
||||
// «Prospección» (catálogo `alfa_objetivosdeactividades`), para programar prospección sobre cuentas sin oportunidad,
|
||||
// y los 4 que Marco agregó el 2026-11-19 (no entran al Agendador masivo). Los nombres deben coincidir EXACTO con
|
||||
// Dynamics: el servidor busca el GUID por nombre (`objetivosPorNombre`). Catálogo completo y decisiones:
|
||||
// Proyectos/Análisis e Informes/Analitica de CRM/referencia-objetivos-de-actividad.md
|
||||
export const OBJETIVOS_LIBRES = [
|
||||
"Prospección",
|
||||
...OBJETIVOS_AGENDADOR,
|
||||
"Reunión Técnica",
|
||||
"Recopilación Proyecto SW",
|
||||
"Retención",
|
||||
"Cobro Factura",
|
||||
];
|
||||
|
||||
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 = [];
|
||||
const paso = AGENDADOR.paso[tipo];
|
||||
for (const [a, b] of AGENDADOR.franjas) for (let s = a; s + dur <= b; s += paso) out.push(s);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Horas (HH:MM) que de verdad se pueden ofrecer para `tipo` en `dia`: si es hoy, solo las futuras (con un margen de
|
||||
// 5 min por lo que tarda el clic) y sin las que choquen con los bloques ya ocupados (`bloques`: [[ini, fin], …] en
|
||||
// minutos). Para otros días devuelve el horario completo. El servidor (`validar`) vuelve a comprobar todo.
|
||||
export function horasLibres({ tipo, dia, hoy, ahoraMin, bloques }) {
|
||||
const dur = AGENDADOR.duracion[tipo];
|
||||
return horasDe(tipo)
|
||||
.filter((s) => dia !== hoy || (s >= ahoraMin + 5 && libre(bloques, s, dur)))
|
||||
.map(minAHora);
|
||||
}
|
||||
|
||||
// «8:30–12:00 y 13:30–17:00», para los textos de ayuda y avisos (siempre sale de AGENDADOR.franjas).
|
||||
export const textoHorario = () =>
|
||||
AGENDADOR.franjas.map(([a, b]) => `${minAHora(a).replace(/^0/, "")}–${minAHora(b).replace(/^0/, "")}`).join(" y ");
|
||||
|
||||
// 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(porPrioridadSugerida);
|
||||
const items = [];
|
||||
for (const c of orden) {
|
||||
const lugar = colocar({ tipo, dias, cuenta, ocup, hoy, ahoraMin, urgente: (c.pct || 0) >= 80 || c.prioRank === 0 });
|
||||
items.push({ ...baseItem(c, tipo), dia: lugar?.dia || null, hora: lugar?.hora || null, sinCupo: !lugar, incluir: !!lugar });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
// Prioridad: forecast más alto primero; a igual forecast, el cierre estimado más próximo primero
|
||||
// (las ya vencidas, antes que todas); luego mayor valor.
|
||||
export const porPrioridad = (x, y) =>
|
||||
(y.pct || 0) - (x.pct || 0) ||
|
||||
(x.cierre || "9999-12-31").localeCompare(y.cierre || "9999-12-31") ||
|
||||
(y.valor || 0) - (x.valor || 0);
|
||||
|
||||
// Fila del agendador a partir de una oportunidad candidata (sin día/hora todavía).
|
||||
export function baseItem(c, tipo) {
|
||||
return {
|
||||
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,
|
||||
tipoOpp: c.tipo || null,
|
||||
plan: c.plan || null,
|
||||
forecast: c.forecast || null,
|
||||
env: c.env ?? null,
|
||||
dsa: c.dsa ?? null,
|
||||
cierre: c.cierre || null,
|
||||
prioNivel: c.prioNivel || null,
|
||||
prioRank: c.prioRank ?? null,
|
||||
prioMotivos: c.prioMotivos || [],
|
||||
tipo,
|
||||
objetivo: c.objetivoSugerido || "",
|
||||
gv: false, // «Con GV»: participa Gerencia Comercial (solo llamadas y visitas)
|
||||
};
|
||||
}
|
||||
|
||||
// Suma lo ya decidido (filas marcadas, con día/hora fijos) a lo existente, para que la propuesta del
|
||||
// resto se acomode ALREDEDOR sin pisarlo ni pasarse de los máximos por día.
|
||||
export function sumarFijos(existentes, bloques, items) {
|
||||
const ex = {};
|
||||
Object.entries(existentes || {}).forEach(([d, c]) => { ex[d] = { ...c }; });
|
||||
const bl = {};
|
||||
Object.entries(bloques || {}).forEach(([d, b]) => { bl[d] = [...b]; });
|
||||
for (const it of items) {
|
||||
if (!it.dia) continue;
|
||||
(ex[it.dia] ||= cuentaVacia())[it.tipo]++;
|
||||
if (it.tipo !== "Tarea" && it.hora) {
|
||||
const s = horaAMin(it.hora);
|
||||
if (s != null) (bl[it.dia] ||= []).push([s, s + AGENDADOR.duracion[it.tipo]]);
|
||||
}
|
||||
}
|
||||
return { existentes: ex, bloques: bl };
|
||||
}
|
||||
|
||||
// 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.
|
||||
// `objetivos`: catálogo permitido (el Agendador masivo usa OBJETIVOS_AGENDADOR; el seguimiento, OBJETIVOS_LIBRES).
|
||||
export function validar({ items, dias, existentes, bloques, hoy, ahoraMin, objetivos = OBJETIVOS_AGENDADOR }) {
|
||||
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.includes(it.objetivo)) marca(it.key, "Objetivo no permitido.");
|
||||
if (it.gv && it.tipo === "Tarea") marca(it.key, "Las tareas no llevan participación de Gerencia (GV).");
|
||||
if (!dias.includes(it.dia)) { marca(it.key, "Elige un día hábil dentro de los días de agendado (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 (${textoHorario()}).`); 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;
|
||||
}
|
||||
// La descripción de una CITA es la invitación que Outlook/Teams envía al contacto: se deja vacía para que
|
||||
// ningún comentario interno llegue por accidente a un cliente (solicitado por el equipo, 2026-11-07).
|
||||
// Llamadas y tareas son internas: conservan la marca de origen.
|
||||
export function descripcionDe(it, creadoPor) {
|
||||
if (it.tipo === "Cita") return undefined;
|
||||
return `Creada por el agendador de actividades (${creadoPor}).`;
|
||||
}
|
||||
|
||||
// «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);
|
||||
64
app/lib/agendadorLotes.js
Normal file
64
app/lib/agendadorLotes.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
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 recientes de un ejecutivo (las más recientes primero).
|
||||
export function getLotesRecientes(ownerId) {
|
||||
return db
|
||||
.prepare("SELECT * FROM agendador_lote WHERE owner_id = ? ORDER BY id DESC LIMIT 20")
|
||||
.all(ownerId)
|
||||
.map(fila);
|
||||
}
|
||||
|
||||
// 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
|
||||
);
|
||||
}
|
||||
111
app/lib/agendadorServer.js
Normal file
111
app/lib/agendadorServer.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// 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 { GC, GV_USUARIO } from "./participantes";
|
||||
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),
|
||||
...(descripcionDe(it, creadoPor) ? { 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]));
|
||||
// Visitas creadas por la app (Agendador y seguimiento): lugar «Oficina del cliente» por defecto (decisión de Marco, 2026-11-10).
|
||||
if (it.tipo === "Cita") body.location = "Oficina del cliente";
|
||||
// «Llamar de» y «Propietario» salen con el propietario de la oportunidad (`ownerid` arriba): Dynamics
|
||||
// completa «de» solo. Verificado por Marco con llamadas reales del agendador (2026-11-06).
|
||||
if (it.tipo === "Llamada") body.directioncode = true;
|
||||
// «Con GV» (Gerencia Comercial participa): queda en el campo Participantes de la actividad. Solo llamadas y visitas.
|
||||
if (it.gv) body.alfa_participantes = GC;
|
||||
// Solo en CITAS: Marco entra como asistente obligatorio (máscara 5) y el propietario como organizador (7), para que
|
||||
// la sincronización del servidor la lleve al Outlook del ejecutivo y Exchange envíe la invitación a Marco. Las llamadas
|
||||
// no llegan al calendario, así que no llevan partes.
|
||||
if (it.gv && it.tipo === "Cita") {
|
||||
body.appointment_activity_parties = [
|
||||
{ participationtypemask: 7, "partyid_systemuser@odata.bind": `/systemusers(${ownerId})` },
|
||||
{ participationtypemask: 5, "partyid_systemuser@odata.bind": `/systemusers(${GV_USUARIO})` },
|
||||
];
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
39
app/lib/campanita.js
Normal file
39
app/lib/campanita.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Campanita de notificaciones (etapa 1, solo web). Función PURA: de las actividades de Dynamics saca lo que pide acción
|
||||
// hoy. Reutiliza el plan (armarPlanPeriodo + listaPlana) para que las vencidas cuadren con el Plan del Día / de Actividades:
|
||||
// - vencida = abierta con día anterior a hoy, o de hoy con la hora ya pasada (porHora: true, igual que el Plan del Día).
|
||||
// - se mira desde el 1.º del mes en curso (el mismo período «Este mes» del Plan de Actividades, al que lleva «Revisar»).
|
||||
// - gerente (administrador sin elegir ejecutivo): solo las actividades con Gerencia Comercial; sin vencidas del equipo.
|
||||
import { armarPlanPeriodo } from "./plan";
|
||||
import { listaPlana } from "./agendaDia";
|
||||
import { minAHora } from "./agendador";
|
||||
|
||||
export const AVISO_MIN = 30; // una llamada/visita que empieza dentro de este margen cuenta en el número rojo
|
||||
|
||||
const compacta = (it, ahoraMin) => ({
|
||||
id: it.id,
|
||||
tipo: it.tipo,
|
||||
hora: it.min == null ? null : minAHora(it.min),
|
||||
cliente: it.opp.cliente || it.opp.nombre || "—",
|
||||
esCaso: it.opp.etn === "incident",
|
||||
esCuenta: it.opp.etn === "account",
|
||||
objetivo: it.objetivo,
|
||||
enMin: !it.esTarea && !it.completada && it.min != null && it.min >= ahoraMin && it.min - ahoraMin <= AVISO_MIN ? it.min - ahoraMin : null,
|
||||
a: it.a, // la actividad completa: la ventana «Gestionar» la necesita tal cual
|
||||
});
|
||||
|
||||
export function armarCampanita(actividades, { hoy, ahoraMin, gerente = false }) {
|
||||
const desde = `${hoy.slice(0, 7)}-01`;
|
||||
const plan = armarPlanPeriodo(actividades, desde, hoy, hoy);
|
||||
let items = listaPlana(plan.secciones, { hoy, ahoraMin, porHora: true });
|
||||
if (gerente) items = items.filter((it) => it.esGC);
|
||||
const vencidas = gerente ? 0 : items.filter((it) => it.vencida).length;
|
||||
const deHoy = items.filter((it) => it.dia === hoy);
|
||||
const proximas = deHoy.filter((it) => !it.completada && !it.vencida).map((it) => compacta(it, ahoraMin));
|
||||
const hechas = deHoy
|
||||
.filter((it) => it.completada)
|
||||
.sort((x, y) => (y.min ?? -1) - (x.min ?? -1))
|
||||
.slice(0, 3)
|
||||
.map((it) => compacta(it, ahoraMin));
|
||||
const pronto = proximas.filter((p) => p.enMin != null).length;
|
||||
return { gerente, hoy, vencidas, pronto, numero: vencidas + pronto, proximas, hechas, totalHoy: deHoy.length };
|
||||
}
|
||||
116
app/lib/campo.js
Normal file
116
app/lib/campo.js
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
// App de campo (PWA, rutas /m/...): funciones PURAS compartidas por las pantallas y las acciones de servidor.
|
||||
// Sin Dynamics ni React. Las reglas de negocio (plan, agenda, participantes) NO se duplican aquí: viven en sus lib.
|
||||
import { nomCorto } from "./derive";
|
||||
|
||||
// ---- Teléfonos y WhatsApp -------------------------------------------------------------------------------------
|
||||
// Número para wa.me: solo dígitos con código de país. Nicaragua = 505. Ocho dígitos → se agrega 505. Los números que
|
||||
// empiezan con 2 son líneas fijas (Managua 2xxx xxxx): WhatsApp no aplica, así que no se ofrece el botón.
|
||||
export function normalizarCelular(s) {
|
||||
let d = String(s || "").replace(/\D/g, "");
|
||||
if (!d) return null;
|
||||
if (d.length === 8) d = `505${d}`;
|
||||
if (d.length === 11 && d.startsWith("505") && !d.startsWith("5052")) return d;
|
||||
return null;
|
||||
}
|
||||
// Para llamar sirve cualquier número (celular o fijo): 8 dígitos locales → +505.
|
||||
export function normalizarTelefono(s) {
|
||||
let d = String(s || "").replace(/\D/g, "");
|
||||
if (!d) return null;
|
||||
if (d.length === 8) return `+505${d}`;
|
||||
if (d.length === 11 && d.startsWith("505")) return `+${d}`;
|
||||
if (d.length >= 9 && d.length <= 15) return `+${d}`;
|
||||
return null;
|
||||
}
|
||||
export const telUrl = (n) => (n ? `tel:${n}` : null);
|
||||
|
||||
const primerNombre = (n) => String(n || "").trim().split(/\s+/)[0] || "";
|
||||
|
||||
// «Hola Ana, le saluda Mirna Obando de ALFA+. » (+ «Le escribo por <oportunidad>. » si viene de una oportunidad).
|
||||
// El ejecutivo siempre revisa y pulsa Enviar: es solo el texto inicial.
|
||||
export function mensajeWA({ contacto, ejecutivo, oportunidad }) {
|
||||
const hola = contacto ? `Hola ${primerNombre(contacto)}` : "Hola";
|
||||
const saluda = ejecutivo ? `le saluda ${nomCorto(ejecutivo)} de ALFA+.` : "le saluda de ALFA+.";
|
||||
return `${hola}, ${saluda} ` + (oportunidad ? `Le escribo sobre ${oportunidad}. ` : "");
|
||||
}
|
||||
export function waUrl(numero, texto) {
|
||||
if (!numero) return null;
|
||||
return `https://wa.me/${numero}${texto ? `?text=${encodeURIComponent(texto)}` : ""}`;
|
||||
}
|
||||
|
||||
// Cómo llegar: coordenadas si existen; si no, la dirección escrita. null si no hay ninguna.
|
||||
export function mapsUrl({ lat, lon, direccion, ciudad, nombre } = {}) {
|
||||
if (typeof lat === "number" && typeof lon === "number" && (lat || lon)) {
|
||||
return `https://www.google.com/maps/dir/?api=1&destination=${lat},${lon}`;
|
||||
}
|
||||
const q = [direccion, ciudad].filter(Boolean).join(", ").trim();
|
||||
if (!q) return null;
|
||||
return `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(`${q}, Nicaragua`)}`;
|
||||
}
|
||||
|
||||
// Destinos de contacto de una cuenta/oportunidad: el contacto principal primero, luego los demás con número, y la
|
||||
// línea de la cuenta. Cada destino trae `tel` (llamar) y `wa` (número de WhatsApp o null).
|
||||
export function destinosDe({ contactos = [], principalId = null, cuenta = null }) {
|
||||
const out = [];
|
||||
const ordenados = [...contactos].sort((a, b) => Number(b.id === principalId) - Number(a.id === principalId));
|
||||
for (const c of ordenados) {
|
||||
const tel = normalizarTelefono(c.celular) || normalizarTelefono(c.fijo);
|
||||
const wa = normalizarCelular(c.celular);
|
||||
if (!tel && !wa) continue;
|
||||
out.push({ id: c.id, nombre: c.nombre, cargo: c.cargo || null, tel, wa, principal: c.id === principalId });
|
||||
}
|
||||
if (cuenta?.telefono) {
|
||||
const tel = normalizarTelefono(cuenta.telefono);
|
||||
const wa = normalizarCelular(cuenta.telefono);
|
||||
if (tel || wa) out.push({ id: "cuenta", nombre: cuenta.nombre || "Cuenta", cargo: "Teléfono de la cuenta", tel, wa, principal: false, esCuenta: true });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Cuentas -------------------------------------------------------------------------------------------------
|
||||
// Categoría de la cuenta: businesstypecode (lo calcula el flujo «Categorizar Cuentas Alfa»).
|
||||
export const CATEGORIAS = { 200003: "Bronce", 200001: "Oro", 200000: "Platinum", 200002: "Diamante" };
|
||||
export const categoriaDe = (code) => CATEGORIAS[code] || null;
|
||||
export const CATEGORIA_COLOR = { Diamante: "#2b8cc4", Platinum: "#6b7c8c", Oro: "#b8870b", Bronce: "#a0623a" };
|
||||
|
||||
// ---- Fechas / presentación ---------------------------------------------------------------------------------
|
||||
const DIAS = ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"];
|
||||
const MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||||
const DIAS_L = ["domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"];
|
||||
const MESES_L = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"];
|
||||
const dowDe = (iso) => new Date(`${iso}T12:00:00Z`).getUTCDay();
|
||||
export const diaCortoES = (iso) => `${DIAS[dowDe(iso)]} ${Number(iso.slice(8, 10))}`;
|
||||
export const diaMesES = (iso) => `${Number(iso.slice(8, 10))} ${MESES[Number(iso.slice(5, 7)) - 1]}`;
|
||||
export const diaLargoES = (iso) => `${DIAS_L[dowDe(iso)]} ${Number(iso.slice(8, 10))} de ${MESES_L[Number(iso.slice(5, 7)) - 1]}`;
|
||||
export const mesLargoES = (iso) => MESES_L[Number(iso.slice(5, 7)) - 1];
|
||||
export const fechaCorta = (iso) => (iso ? `${iso.slice(8, 10)}/${iso.slice(5, 7)}` : "—");
|
||||
export const diasEntreIso = (a, b) => Math.round((Date.parse(`${b}T12:00:00Z`) - Date.parse(`${a}T12:00:00Z`)) / 86400000);
|
||||
|
||||
// Cuántos días faltan (o pasaron) para una fecha: «en 7 días», «hoy», «vencida hace 3 días».
|
||||
export function textoDias(iso, hoy) {
|
||||
if (!iso) return "";
|
||||
const d = diasEntreIso(hoy, iso);
|
||||
if (d === 0) return "hoy";
|
||||
if (d === 1) return "mañana";
|
||||
if (d > 1) return `en ${d} días`;
|
||||
return `venció hace ${-d} ${d === -1 ? "día" : "días"}`;
|
||||
}
|
||||
|
||||
// ---- Opciones de los campos editables de la oportunidad -------------------------------------------------------
|
||||
// Verificadas contra los metadatos de Dynamics el 2026-11-13 (EntityDefinitions de `opportunity`). Si Dynamics cambia un
|
||||
// conjunto de opciones, el servidor rechaza el valor y la app lo avisa: aquí NO se crean ni cambian opciones.
|
||||
export const FORECAST_OPC = [
|
||||
[100000002, "20% Calificada"], [100000003, "40% En Desarrollo"], [100000004, "50% En análisis por el cliente"], [100000005, "60% Terna Proveedores"],
|
||||
[100000006, "70% Negociación"], [100000007, "80% Proveedor Confirmado"], [100000008, "90% Firma de contrato"],
|
||||
];
|
||||
// 0% - Omitida (100000001) existe en el tenant pero se excluye del embudo: no se ofrece desde el teléfono.
|
||||
export const PROB_OPC = [[100000000, "Alta"], [100000001, "Mediana"], [100000003, "Se desconoce"]]; // el conjunto NO tiene «Baja»
|
||||
export const LUZ_OPC = [
|
||||
[11, "Ninguna"], [0, "Precio"], [1, "Cobertura"], [2, "Tiempo de entrega"], [3, "Instalación"], [4, "Sin acceso al decisor"], [5, "Contrato vigente"],
|
||||
[6, "Condiciones contractuales"], [7, "Se desconoce"], [8, "Recursos necesarios"], [9, "Cliente indeciso"], [10, "Otro"], [100000000, "Anti Campeón"],
|
||||
];
|
||||
export const TIPO_OPC = [
|
||||
[100000000, "Venta - Cliente Nuevo"], [100000003, "Cross-Selling"], [100000004, "Up-Selling"], [100000007, "Plan de Cuenta"], [100000009, "No MRR"],
|
||||
[100000001, "Próximo a Vencer 30/60/90"], [100000002, "Contrato vencido"], [100000005, "SAC - Retención"], [100000006, "SAC - Traslado"], [100000008, "SAC - Otros"],
|
||||
];
|
||||
export const MAX_ESTADO_NEGOCIACION = 2000; // MaxLength de alfa_estadodelanegociacion (memo)
|
||||
export const MIN_DESHACER_MS = 10 * 60 * 1000; // «Deshacer» durante 10 minutos
|
||||
41
app/lib/campoPagina.js
Normal file
41
app/lib/campoPagina.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
// Utilidades de servidor para las pantallas de /m: sesión, alcance (mismos permisos que la web) y lista compacta de actividades.
|
||||
import { auth } from "./auth";
|
||||
import { ownerFilter } from "./authz";
|
||||
import { getSystemUsers } from "./queries";
|
||||
import { EJECUTIVOS_VENTA } from "./derive";
|
||||
import { AGENDADOR, localDeIso, minAHora } from "./agendador";
|
||||
import { hoyManagua } from "./plan";
|
||||
|
||||
// Sesión + alcance. Ejecutivo: solo lo suyo. Gerente / asistente: pueden elegir propietario (`?owner=`) o «Todos».
|
||||
export async function contextoCampo(sp) {
|
||||
const session = await auth();
|
||||
if (!session?.email) return null;
|
||||
const scope = ownerFilter(session, typeof sp?.owner === "string" ? sp.owner : undefined, { asistente: true });
|
||||
let owners = [];
|
||||
if (session.isAdmin || scope.asistente) {
|
||||
const users = await getSystemUsers(session.accessToken);
|
||||
owners = users
|
||||
.filter((u) => EJECUTIVOS_VENTA.includes(u.name) || u.email === session.email)
|
||||
.filter((u) => !scope.asistente || AGENDADOR.piloto.includes(u.email))
|
||||
.map((u) => ({ email: u.email, name: u.email === session.email ? `${u.name} (yo)` : u.name }));
|
||||
}
|
||||
const unico = scope.locked ? session.email : scope.emails.length === 1 ? scope.emails[0] : null;
|
||||
return {
|
||||
session, scope, owners, unico,
|
||||
selector: !scope.locked,
|
||||
ownerActual: scope.locked ? "" : scope.emails.length === 1 ? scope.emails[0] : "",
|
||||
hoy: hoyManagua(),
|
||||
ahoraMin: localDeIso(new Date().toISOString()).min,
|
||||
};
|
||||
}
|
||||
|
||||
// Actividad del plan (lib/agendaDia.listaPlana) → objeto simple para el cliente (tarjetas y hoja de acciones).
|
||||
export function compactar(it) {
|
||||
const nombreOpp = it.opp.etn === "opportunity" && it.opp.nombre && it.opp.nombre !== it.opp.cliente ? it.opp.nombre : null;
|
||||
return {
|
||||
id: it.id, tipo: it.tipo, dia: it.dia, hora: it.min == null ? null : minAHora(it.min), min: it.min, dur: it.dur,
|
||||
esTarea: it.esTarea, completada: it.completada, vencida: it.vencida, cliente: it.opp.cliente || it.opp.nombre || "—",
|
||||
oppNombre: nombreOpp, etn: it.opp.etn, refId: it.opp.id, owner: it.owner, objetivo: it.objetivo, sec: it.sec, secTitulo: it.secTitulo,
|
||||
valor: it.valor, gv: it.gv, cruce: it.cruce, esGC: it.esGC, fila: it.fila,
|
||||
};
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue