127 lines
5.3 KiB
JavaScript
127 lines
5.3 KiB
JavaScript
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>
|
|
);
|
|
}
|