informe-comercial-alfa/app/components/Campanita.js

154 lines
6.2 KiB
JavaScript
Raw Normal View History

"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>
);
}