informe-comercial-alfa/app/m/components/CampoShell.js

123 lines
5.2 KiB
JavaScript
Raw Permalink 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 { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { Suspense } from "react";
import Campanita from "../../components/Campanita";
import HojaActividad from "./HojaActividad";
import NuevaMovil from "./NuevaMovil";
import WhatsAppRegistro from "./WhatsAppRegistro";
import { CampoContext } from "../CampoContext";
const TABS = [
["/m/hoy", "☀", "Hoy"],
["/m/calendario", "🗓", "Calendario"],
["/m/semana", "✓", "Semana"],
["/m/tuberia", "◎", "Tubería"],
["/m/cuentas", "🏢", "Cuentas"],
];
const TITULOS = { "/m/hoy": "Hoy", "/m/calendario": "Calendario", "/m/semana": "Mi semana", "/m/tuberia": "Mi tubería", "/m/cuentas": "Mis cuentas" };
const hoyManagua = () => new Intl.DateTimeFormat("en-CA", { timeZone: "America/Managua" }).format(new Date());
function NavTab({ href, ico, txt, activo }) {
const owner = useSearchParams().get("owner");
return (
<Link href={owner ? `${href}?owner=${encodeURIComponent(owner)}` : href} className={`m-tab${activo ? " on" : ""}`} aria-current={activo ? "page" : undefined}>
<i aria-hidden="true">{ico}</i><span>{txt}</span>
</Link>
);
}
// Aviso «Sin conexión · actualizado HH:MM»: el service worker dice si lo que se ve salió de su copia de /m/hoy.
function EstadoConexion() {
const [off, setOff] = useState(null);
useEffect(() => {
const pregunta = () => {
const c = navigator.serviceWorker?.controller;
if (!c) return;
const ch = new MessageChannel();
ch.port1.onmessage = (e) => setOff(e.data?.cache ? e.data : null);
c.postMessage({ q: "estado", url: location.pathname }, [ch.port2]);
};
pregunta();
const a = () => pregunta();
window.addEventListener("online", a);
window.addEventListener("offline", a);
navigator.serviceWorker?.addEventListener("controllerchange", pregunta);
return () => { window.removeEventListener("online", a); window.removeEventListener("offline", a); };
}, []);
if (!off) return null;
return <div className="m-off" role="status">Sin conexión · actualizado {off.hora}</div>;
}
export default function CampoShell({ session, onSignIn, onSignOut, children }) {
const path = usePathname();
const router = useRouter();
const [hoja, setHoja] = useState(null);
const [nuevo, setNuevo] = useState(null);
const [hoy, setHoy] = useState("");
useEffect(() => setHoy(hoyManagua()), []);
const ctx = useMemo(() => ({ abrirActividad: setHoja, abrirNuevo: (p) => setNuevo(p || {}), hoy }), [hoy]);
const principal = TITULOS[path] ? path : null;
useEffect(() => {
// Service worker (solo /m): lectura sin conexión de /m/hoy. Nunca guarda sesión ni otras rutas.
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/campo-sw.js", { scope: "/m/" }).catch(() => {});
}, []);
useEffect(() => {
const f = (e) => setNuevo(e.detail || {});
window.addEventListener("campo:nuevo", f);
return () => window.removeEventListener("campo:nuevo", f);
}, []);
function abrirFab() {
const el = document.querySelector("[data-campo-ref]");
const ref = el ? { tipo: el.dataset.campoRef, id: el.dataset.campoId, nombre: el.dataset.campoNombre } : undefined;
setNuevo(ref ? { ref } : {});
}
async function salir() {
try { await caches.delete("campo-hoy"); } catch { /* ignorar */ }
try { localStorage.removeItem("campo.owner"); } catch { /* ignorar */ }
onSignOut && onSignOut();
}
if (!session?.email) {
return (
<div className="m-app m-sin">
<div className="m-login">
<h1>ALFA+ Campo</h1>
<p>Inicia sesión con tu cuenta de Alfanumeric para ver tu día.</p>
<form action={onSignIn}><button type="submit" className="m-btn pri">Iniciar sesión</button></form>
</div>
</div>
);
}
return (
<CampoContext.Provider value={ctx}>
<div className="m-app" data-campo-ok="1">
{principal && (
<header className="m-top">
<h1>{TITULOS[principal]}</h1>
<Campanita rutaPlan="/m/hoy" rutaVenc="/m/semana?venc=1" />
</header>
)}
<EstadoConexion />
<main className={principal ? "m-main" : "m-main ficha"}>{children}</main>
<nav className="m-nav" aria-label="Secciones">
<Suspense fallback={null}>
{TABS.map(([h, i, t]) => <NavTab key={h} href={h} ico={i} txt={t} activo={path === h || (h === "/m/cuentas" && path.startsWith("/m/cuentas")) || (h === "/m/tuberia" && path.startsWith("/m/oportunidad"))} />)}
</Suspense>
</nav>
<button type="button" className="m-fab" aria-label="Registrar o agendar una actividad" onClick={abrirFab}>+</button>
{hoja && <HojaActividad item={hoja} onCerrar={() => setHoja(null)} />}
{nuevo && <NuevaMovil hoy={hoy || hoyManagua()} preset={nuevo} onCerrar={() => { setNuevo(null); }} />}
<WhatsAppRegistro />
<form action={salir} className="m-pie"><button type="submit" className="m-lnk">Cerrar sesión · {session.email}</button> · <Link href="/plan" className="m-lnk">Versión web</Link></form>
</div>
</CampoContext.Provider>
);
}