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

230 lines
9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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