526 lines
31 KiB
JavaScript
526 lines
31 KiB
JavaScript
"use client";
|
||
|
||
import { useEffect, useMemo, useState, useTransition } from "react";
|
||
import { useRouter } from "next/navigation";
|
||
import Link from "next/link";
|
||
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,
|
||
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 viene activado de entrada: el
|
||
// ejecutivo ve todas sus oportunidades abiertas (2026-11-06) y es él quien las acota.
|
||
// «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: "prio", lbl: "Prioridad", valor: (c) => c.prioNivel, orden: NIVELES_PRIO },
|
||
{ k: "tipo", lbl: "Tipo de oportunidad", valor: (c) => c.tipo || "(sin tipo)" },
|
||
{ 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 estimado", 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({ ownerEmail, ownerName, hoy, ahoraMin, candidatos, actPorOpp, existentes, bloques, lotes }) {
|
||
const router = useRouter();
|
||
const [pendiente, empezar] = useTransition();
|
||
const maxFecha = fechaMaxima(hoy);
|
||
const [fecha, setFecha] = useState(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(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, 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, 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;
|
||
});
|
||
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 });
|
||
};
|
||
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(", ");
|
||
if (!window.confirm(`Se crearán en Dynamics ${marcadas.length} actividades (${resumen}) para ${ownerName}, a su nombre. ¿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 })),
|
||
});
|
||
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.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 sinCupo = filas.filter((i) => i.sinCupo && !i.dia).length;
|
||
const fueraDeFiltro = filas.filter((f) => f.fueraDelFiltro).length;
|
||
const filasTabla = [...creadas, ...filas];
|
||
|
||
return (
|
||
<section className="plan-agd agd-modulo no-print">
|
||
<header className="agd-banner">
|
||
<div>
|
||
<h1 className="agd-banner-t">📅 Agendador de actividades</h1>
|
||
<p className="agd-banner-s">Módulo independiente del Plan de Actividades · {ownerName} <span className="agd-piloto">piloto</span></p>
|
||
</div>
|
||
<Link href={`/actividades?owner=${ownerEmail}`} className="agd-banner-enlace">Ver el Plan de Actividades →</Link>
|
||
</header>
|
||
|
||
<div className="agd-cuerpo">
|
||
<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 día, la hora, el tipo o el objetivo.</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 entre 9:00–12:00 y 14:00–16:00; máximo por día: {AGENDADOR.topes.Llamada} llamadas, {AGENDADOR.topes.Cita} visitas y {AGENDADOR.topes.Tarea} tareas.
|
||
Se muestran <b>todas las oportunidades abiertas</b> del ejecutivo, sin importar su fecha de cierre.
|
||
</p>
|
||
</div>
|
||
|
||
{candidatos.length === 0 && creadas.length === 0 ? (
|
||
<p className="agd-vacio">{ownerName} no tiene oportunidades abiertas con fecha de cierre estimada.</p>
|
||
) : (
|
||
<>
|
||
<div className="agd-fecha">
|
||
<label htmlFor="agd-fecha-i"><b>Agendar a partir del:</b></label>
|
||
<input id="agd-fecha-i" type="date" value={fecha} min={hoy} max={maxFecha} onChange={(e) => cambiarFecha(e.target.value)} disabled={pendiente} />
|
||
<span className="hint">
|
||
Se reparte en: <b>{dias.map((d) => diaCorto(d)).join(" · ")}</b> · puedes elegir hasta el {fechaLarga(maxFecha)}
|
||
</span>
|
||
</div>
|
||
|
||
<div className="agd-dias">
|
||
{dias.map((d) => {
|
||
const c = val.porDia[d] || { Llamada: 0, Cita: 0, Tarea: 0, ...(existentes[d] || {}) };
|
||
const exc = TIPOS_AGENDADOR.some((t) => c[t] > AGENDADOR.topes[t]);
|
||
return (
|
||
<span key={d} className={`agd-dia${exc ? " mal" : ""}`} title="Lo que ya tiene agendado ese día más lo que marcaste">
|
||
<b>{diaCorto(d)}</b> {c.Llamada} llam. · {c.Cita} vis. · {c.Tarea} tar.
|
||
</span>
|
||
);
|
||
})}
|
||
</div>
|
||
|
||
<div className="agd-buscar">
|
||
<input
|
||
type="search"
|
||
value={busqueda}
|
||
onChange={(e) => setBusqueda(e.target.value)}
|
||
placeholder="Buscar cliente u oportunidad por nombre (o parte del nombre)…"
|
||
aria-label="Buscar cliente u oportunidad"
|
||
/>
|
||
{busqueda && <button type="button" className="agd-btn-sec" onClick={() => setBusqueda("")}>Borrar búsqueda</button>}
|
||
</div>
|
||
|
||
<div className="agd-filtros">
|
||
{FILTROS.map((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" 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>
|
||
);
|
||
})}
|
||
{hayFiltros && <button type="button" className="agd-btn-sec" onClick={() => setFiltros(SIN_FILTROS)}>Limpiar filtros</button>}
|
||
</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>
|
||
)))}
|
||
</div>
|
||
)}
|
||
|
||
<div className="agd-barra">
|
||
<label htmlFor="agd-tipo">Tipo de actividad:</label>
|
||
<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 className="agd-check">
|
||
<input type="checkbox" checked={ocultarConAct} onChange={(e) => setOcultarConAct(e.target.checked)} /> Ocultar las que ya tienen actividad en esos días
|
||
</label>
|
||
</div>
|
||
<p className="agd-contador">
|
||
Mostrando <b>{coinciden.length}</b> de <b>{disponibles.length}</b> oportunidad{disponibles.length === 1 ? "" : "es"} abiertas
|
||
{(hayFiltros || q || ocultarConAct) && <> · <button type="button" className="agd-btn-sec" onClick={() => { setFiltros(SIN_FILTROS); setBusqueda(""); setOcultarConAct(false); }}>Quitar filtros y búsqueda</button></>}
|
||
{fueraDeFiltro > 0 && ` · ${fueraDeFiltro} marcada${fueraDeFiltro === 1 ? "" : "s"} fuera del filtro (se conservan)`}
|
||
</p>
|
||
|
||
{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={() => { setFiltros(SIN_FILTROS); setBusqueda(""); setOcultarConAct(false); }}>Quitar filtros y búsqueda</button>
|
||
</p>
|
||
) : (
|
||
<>
|
||
<div className="agd-barra">
|
||
<button type="button" className="agd-btn-sec" onClick={() => marcarTodas(true)} disabled={pendiente || !filas.length}>Marcar todas las que se ven</button>
|
||
<button type="button" className="agd-btn-sec" onClick={() => marcarTodas(false)} disabled={pendiente || !marcadas.length}>Desmarcar todas</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>
|
||
<span className="hint">
|
||
{marcadas.length} marcada{marcadas.length === 1 ? "" : "s"} para crear
|
||
{sinCupo > 0 && ` · ${sinCupo} sin cupo en esos días con estos máximos (puedes elegirles un día a mano)`}
|
||
</span>
|
||
</div>
|
||
|
||
<div className="ts agd-ts">
|
||
<table className="agd-tbl">
|
||
<colgroup>
|
||
<col style={{ width: "3%" }} />
|
||
<col style={{ width: "17%" }} />
|
||
<col style={{ width: "9%" }} />
|
||
<col style={{ width: "10%" }} />
|
||
<col style={{ width: "9%" }} />
|
||
<col style={{ width: "7%" }} />
|
||
<col style={{ width: "6%" }} />
|
||
<col style={{ width: "8%" }} />
|
||
<col style={{ width: "7%" }} />
|
||
<col style={{ width: "6%" }} />
|
||
<col style={{ width: "9%" }} />
|
||
<col style={{ width: "9%" }} />
|
||
</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>Tipo y plan de cierre</th>
|
||
<th><button type="button" className="agd-th-b" onClick={() => ordenarPor("forecast")}>Previsión{flecha("forecast")}</button></th>
|
||
<th><button type="button" className="agd-th-b" onClick={() => ordenarPor("cierre")}>Cierre{flecha("cierre")}</button></th>
|
||
<th className="num"><button type="button" className="agd-th-b" onClick={() => ordenarPor("valor")}>Valor{flecha("valor")}</button></th>
|
||
<th>Actividad</th>
|
||
<th>Día</th>
|
||
<th>Hora</th>
|
||
<th>Objetivo</th>
|
||
<th>Avisos</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;
|
||
return (
|
||
<tr key={it.key} className={hecha ? "agd-hecha" : it.incluir ? "agd-marcada" : bloqueada ? "agd-con-act" : undefined}>
|
||
<td>
|
||
<input type="checkbox" checked={!!it.incluir && !hecha} disabled={hecha || bloqueada || pendiente || (!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>}
|
||
</td>
|
||
<td>
|
||
{it.prioNivel && (
|
||
<>
|
||
<span className={`agd-prio p-${NIVELES_PRIO.indexOf(it.prioNivel)}`}>{it.prioNivel}</span>
|
||
<div className="agd-sub">{(it.prioMotivos || []).join(" · ")}</div>
|
||
</>
|
||
)}
|
||
</td>
|
||
<td>
|
||
{it.tipoOpp || "—"}
|
||
<div className="agd-sub">{it.plan || "Sin plan de cierre"}</div>
|
||
</td>
|
||
<td>{it.forecast || "—"}</td>
|
||
<td className={vencida ? "agd-venc" : undefined}>
|
||
{it.cierre ? fechaLarga(it.cierre) : "—"}
|
||
{vencida && <div className="agd-sub">vencida</div>}
|
||
</td>
|
||
<td className="num">{money(it.valor)}</td>
|
||
<td>
|
||
<select value={it.tipo} disabled={hecha || bloqueada || pendiente} onChange={(e) => cambiarTipo(it, e.target.value)}>
|
||
{TIPOS_AGENDADOR.map((t) => <option key={t} value={t}>{t}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>
|
||
<select value={it.dia || ""} disabled={hecha || bloqueada || pendiente} onChange={(e) => cambiarDia(it, e.target.value)}>
|
||
<option value="">— elegir —</option>
|
||
{dias.map((d) => <option key={d} value={d}>{diaCorto(d)}</option>)}
|
||
</select>
|
||
</td>
|
||
<td>
|
||
{it.tipo === "Tarea" ? (
|
||
<span title="Las tareas vencen a las 16:00">vence {minAHora(AGENDADOR.horaTarea)}</span>
|
||
) : (
|
||
<select value={it.hora || ""} disabled={hecha || bloqueada || pendiente || !it.dia} onChange={(e) => editar(it, { hora: e.target.value })}>
|
||
<option value="">—</option>
|
||
{horas.map((h) => <option key={h} value={h}>{h}</option>)}
|
||
</select>
|
||
)}
|
||
</td>
|
||
<td>
|
||
<select value={it.objetivo} disabled={hecha || bloqueada || pendiente} 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>
|
||
<td>
|
||
{hecha ? (
|
||
<a className="agd-ok" href={actividadUrl({ tipo: it.creada.tipo, id: it.creada.activityId })} target="_blank" rel="noreferrer">✓ Creada · abrir en CRM</a>
|
||
) : bloqueada ? (
|
||
<span className="hint">Ya tiene una actividad agendada el {fechaLarga(it.conActividad)}.</span>
|
||
) : it.sinCupo && !it.dia ? (
|
||
<span className="agd-mal">Sin cupo en esos días: elige un día.</span>
|
||
) : it.incluir && probs.length ? (
|
||
<span className="agd-mal">{probs.join(" ")}</span>
|
||
) : it.fueraDelFiltro ? (
|
||
<span className="hint">Marcada; no coincide con el filtro actual.</span>
|
||
) : it.tipo === "Cita" && it.incluir ? (
|
||
<span className="hint">Se crea genérica: completa lugar y participantes en el CRM.</span>
|
||
) : null}
|
||
</td>
|
||
</tr>
|
||
);
|
||
})}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
|
||
<div className="agd-pie">
|
||
<button type="button" className="agd-btn" disabled={pendiente || !marcadas.length || !val.ok} onClick={crear}>
|
||
{pendiente ? "Trabajando…" : `Crear ${marcadas.length} actividad${marcadas.length === 1 ? "" : "es"} en Dynamics`}
|
||
</button>
|
||
{!val.ok && marcadas.length > 0 && <span className="agd-mal">Corrige los avisos en rojo para poder crear.</span>}
|
||
{marcadas.length === 0 && <span className="hint">Marca al menos una oportunidad para poder crear.</span>}
|
||
</div>
|
||
{hayCitas && (
|
||
<p className="hint">Las visitas se crean con lo básico (fecha, hora, objetivo, oportunidad). Después de crearlas, abre cada una con «abrir en CRM» para agregar el lugar y los participantes.</p>
|
||
)}
|
||
</>
|
||
)}
|
||
</>
|
||
)}
|
||
|
||
{aviso && <p className={aviso.mal ? "agd-mal" : "agd-ok"} role="status">{aviso.texto}</p>}
|
||
{resultado && (
|
||
<div className="agd-res">
|
||
<strong>Tanda #{resultado.loteId}:</strong> {resultado.creadas} creada(s){resultado.errores ? `, ${resultado.errores} con error` : ""}{resultado.omitidas ? `, ${resultado.omitidas} omitida(s)` : ""}.
|
||
{resultado.resultados.filter((x) => x.estado !== "creada").map((x) => (
|
||
<div key={x.oppId} className="agd-mal">{x.nombre || x.oppId}: {x.error}</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
|
||
{lotes.length > 0 && (
|
||
<details className="agd-lotes">
|
||
<summary>Tandas 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) · {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>
|
||
)}
|
||
</div>
|
||
</section>
|
||
);
|
||
}
|