284 lines
12 KiB
JavaScript
284 lines
12 KiB
JavaScript
|
|
import { Suspense } from "react";
|
|||
|
|
import { auth } from "../lib/auth";
|
|||
|
|
import { ownerFilter } from "../lib/authz";
|
|||
|
|
import {
|
|||
|
|
getActividades, getClosedRange, getSystemUsers, getOportunidadesSemana, resolveOwnerId, VENTA_TYPE_FILTER, REN_TYPE_FILTER,
|
|||
|
|
} from "../lib/queries";
|
|||
|
|
import { getVersionesPlan, getPlanCerrado, getPlanesListosDelDia } from "../lib/planCerrado";
|
|||
|
|
import { EJECUTIVOS_VENTA } from "../lib/derive";
|
|||
|
|
import { money } from "../lib/constants";
|
|||
|
|
import {
|
|||
|
|
armarPlan, sinActividadAgendada, resumenEquipo, compararConFoto, hoyManagua, addDays, semanaDe, SECCIONES,
|
|||
|
|
} from "../lib/plan";
|
|||
|
|
import PlanListoBoton from "../components/plan/PlanListoBoton";
|
|||
|
|
import PlanSeccion from "../components/plan/PlanSeccion";
|
|||
|
|
import MrrSegmentos from "../components/plan/MrrSegmentos";
|
|||
|
|
import SinActividadPanel from "../components/plan/SinActividadPanel";
|
|||
|
|
import PlanVsReal from "../components/plan/PlanVsReal";
|
|||
|
|
import LoginPrompt from "../components/LoginPrompt";
|
|||
|
|
import OwnerControl from "../components/OwnerControl";
|
|||
|
|
import ErrorNotice from "../components/ErrorNotice";
|
|||
|
|
import PlanControles from "../components/plan/PlanControles";
|
|||
|
|
|
|||
|
|
export const dynamic = "force-dynamic";
|
|||
|
|
|
|||
|
|
const fechaTxt = (iso) => iso.split("-").reverse().join("/");
|
|||
|
|
const suma = (rows) => rows.reduce((t, o) => t + (o.actual || 0), 0);
|
|||
|
|
|
|||
|
|
// Momento en que se marcó un plan (se guarda en UTC), en hora de Nicaragua: «26/10 8:41 a. m.».
|
|||
|
|
function fmtMarca(iso) {
|
|||
|
|
const d = new Date(iso);
|
|||
|
|
const dia = new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", day: "2-digit", month: "2-digit" }).format(d);
|
|||
|
|
const hora = new Intl.DateTimeFormat("es-NI", { timeZone: "America/Managua", hour: "numeric", minute: "2-digit" }).format(d);
|
|||
|
|
return `${dia} ${hora}`;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Casos y cuentas no tienen valor estimado: si la celda no suma valor, solo se muestra la cantidad.
|
|||
|
|
const celda = (c) => (c.n ? (c.valor ? `${c.n} · ${money(c.valor)}` : `${c.n}`) : "—");
|
|||
|
|
|
|||
|
|
function ResumenEquipo({ resumen, fecha, ventasTotal, renovTotal, listoPorNombre }) {
|
|||
|
|
const { lineas, total, otros } = resumen;
|
|||
|
|
const nListos = lineas.filter((l) => listoPorNombre[l.nombre]).length;
|
|||
|
|
return (
|
|||
|
|
<section className="plan-equipo">
|
|||
|
|
<h1 className="plan-titulo plan-titulo-eq">PLAN DEL DÍA — RESUMEN DEL EQUIPO</h1>
|
|||
|
|
<div className="plan-meta">
|
|||
|
|
<span><strong>Fecha:</strong> {fechaTxt(fecha)}</span>
|
|||
|
|
</div>
|
|||
|
|
<div className="kpis plan-kpis">
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{money(ventasTotal)}</span>
|
|||
|
|
<span className="l">Ventas logradas del mes (al {fechaTxt(fecha)})</span>
|
|||
|
|
</div>
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{money(renovTotal)}</span>
|
|||
|
|
<span className="l">Renovaciones logradas del mes (al {fechaTxt(fecha)})</span>
|
|||
|
|
</div>
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{total.actHechas} de {total.actTotal}</span>
|
|||
|
|
<span className="l">Actividades del día completadas</span>
|
|||
|
|
</div>
|
|||
|
|
</div>
|
|||
|
|
<div className="ts">
|
|||
|
|
<table className="plan-eq-tbl">
|
|||
|
|
<thead>
|
|||
|
|
<tr>
|
|||
|
|
<th>Ejecutivo</th>
|
|||
|
|
{SECCIONES.map((s) => <th key={s.key} className="num">{s.titulo}</th>)}
|
|||
|
|
<th className="num">Completadas</th>
|
|||
|
|
<th className="num">Plan listo</th>
|
|||
|
|
<th className="num">Ventas del mes</th>
|
|||
|
|
<th className="num">Renov. del mes</th>
|
|||
|
|
</tr>
|
|||
|
|
</thead>
|
|||
|
|
<tbody>
|
|||
|
|
{lineas.map((l) => (
|
|||
|
|
<tr key={l.nombre}>
|
|||
|
|
<td>{l.nombre}</td>
|
|||
|
|
{SECCIONES.map((s) => <td key={s.key} className="num">{celda(l.secs[s.key])}</td>)}
|
|||
|
|
<td className="num">{l.actTotal ? `${l.actHechas} de ${l.actTotal}` : "—"}</td>
|
|||
|
|
<td className="num">{listoPorNombre[l.nombre] ? `✓ ${listoPorNombre[l.nombre]}` : "—"}</td>
|
|||
|
|
<td className="num">{money(l.ventasMes)}</td>
|
|||
|
|
<td className="num">{money(l.renovMes)}</td>
|
|||
|
|
</tr>
|
|||
|
|
))}
|
|||
|
|
{otros && (
|
|||
|
|
<tr className="plan-otros">
|
|||
|
|
<td>Otros propietarios</td>
|
|||
|
|
{SECCIONES.map((s) => <td key={s.key} className="num">—</td>)}
|
|||
|
|
<td className="num">—</td>
|
|||
|
|
<td className="num">—</td>
|
|||
|
|
<td className="num">{money(otros.ventasMes)}</td>
|
|||
|
|
<td className="num">{money(otros.renovMes)}</td>
|
|||
|
|
</tr>
|
|||
|
|
)}
|
|||
|
|
</tbody>
|
|||
|
|
<tfoot>
|
|||
|
|
<tr>
|
|||
|
|
<td><strong>Total equipo</strong></td>
|
|||
|
|
{SECCIONES.map((s) => <td key={s.key} className="num"><strong>{celda(total.secs[s.key])}</strong></td>)}
|
|||
|
|
<td className="num"><strong>{total.actTotal ? `${total.actHechas} de ${total.actTotal}` : "—"}</strong></td>
|
|||
|
|
<td className="num"><strong>{nListos} de {lineas.length}</strong></td>
|
|||
|
|
<td className="num"><strong>{money(total.ventasMes)}</strong></td>
|
|||
|
|
<td className="num"><strong>{money(total.renovMes)}</strong></td>
|
|||
|
|
</tr>
|
|||
|
|
</tfoot>
|
|||
|
|
</table>
|
|||
|
|
</div>
|
|||
|
|
<p className="hint plan-eq-nota">
|
|||
|
|
Cada celda: oportunidades, casos o cuentas con actividad agendada ese día · valor estimado. Ventas y renovaciones del mes
|
|||
|
|
suman lo ganado por cada ejecutivo hasta el {fechaTxt(fecha)}.
|
|||
|
|
</p>
|
|||
|
|
</section>
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
export default async function PlanDelDia({ searchParams }) {
|
|||
|
|
const session = await auth();
|
|||
|
|
if (!session?.email) return <LoginPrompt />;
|
|||
|
|
|
|||
|
|
const sp = await searchParams;
|
|||
|
|
const scope = ownerFilter(session, sp.owner);
|
|||
|
|
const hoy = hoyManagua();
|
|||
|
|
const fecha = /^\d{4}-\d{2}-\d{2}$/.test(sp.fecha || "") ? sp.fecha : hoy;
|
|||
|
|
const desdeMes = `${fecha.slice(0, 7)}-01`;
|
|||
|
|
const hastaDia = addDays(fecha, 1);
|
|||
|
|
const { lunes, domingo } = semanaDe(fecha);
|
|||
|
|
|
|||
|
|
let actividades, ventas, renovaciones, allUsers, oppsSemana;
|
|||
|
|
try {
|
|||
|
|
[actividades, ventas, renovaciones, allUsers, oppsSemana] = await Promise.all([
|
|||
|
|
getActividades(session.accessToken, scope),
|
|||
|
|
getClosedRange(session.accessToken, scope, 1, desdeMes, hastaDia, undefined, VENTA_TYPE_FILTER),
|
|||
|
|
getClosedRange(session.accessToken, scope, 1, desdeMes, hastaDia, undefined, REN_TYPE_FILTER),
|
|||
|
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
|||
|
|
getOportunidadesSemana(session.accessToken, scope, lunes, domingo),
|
|||
|
|
]);
|
|||
|
|
} catch (error) {
|
|||
|
|
return <ErrorNotice error={error} />;
|
|||
|
|
}
|
|||
|
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
|||
|
|
const plan = armarPlan(actividades, fecha, hoy);
|
|||
|
|
|
|||
|
|
// "Todos" (sin propietario elegido) = el equipo de ventas curado, como en el resto del informe.
|
|||
|
|
const sinActividad = sinActividadAgendada(
|
|||
|
|
scope.emails?.length ? oppsSemana : oppsSemana.filter((o) => EJECUTIVOS_VENTA.includes(o.owner)),
|
|||
|
|
actividades,
|
|||
|
|
fecha
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
const quien = scope.locked
|
|||
|
|
? session.email
|
|||
|
|
: scope.emails.length === 1
|
|||
|
|
? owners.find((o) => o.email === scope.emails[0])?.name || scope.emails[0]
|
|||
|
|
: scope.emails.length
|
|||
|
|
? `${scope.emails.length} ejecutivos`
|
|||
|
|
: "Equipo";
|
|||
|
|
const tituloPdf = `Plan del día – ${quien} – ${fecha}`;
|
|||
|
|
|
|||
|
|
// Resumen del equipo: solo para el administrador cuando ve a más de un ejecutivo.
|
|||
|
|
const verEquipo = !scope.locked && scope.emails.length !== 1 && owners.length > 0;
|
|||
|
|
const nombresEquipo = owners
|
|||
|
|
.filter((o) => !scope.emails.length || scope.emails.includes(o.email))
|
|||
|
|
.map((o) => o.name);
|
|||
|
|
const resumen = verEquipo ? resumenEquipo(plan, nombresEquipo, ventas, renovaciones) : null;
|
|||
|
|
|
|||
|
|
// Plan cerrado (etapa 3): solo cuando se ve el plan de UN ejecutivo (el vendedor, o el
|
|||
|
|
// administrador con un solo propietario elegido). La foto se identifica por systemuserid.
|
|||
|
|
const unicoEmail = scope.locked ? session.email : scope.emails.length === 1 ? scope.emails[0] : null;
|
|||
|
|
let unicoId = null;
|
|||
|
|
let unicoNombre = null;
|
|||
|
|
let versiones = [];
|
|||
|
|
let foto = null;
|
|||
|
|
let comparacion = null;
|
|||
|
|
if (unicoEmail) {
|
|||
|
|
const u = owners.find((o) => o.email === unicoEmail);
|
|||
|
|
unicoId = u?.id || (await resolveOwnerId(unicoEmail, session.accessToken));
|
|||
|
|
unicoNombre = u?.name || quien;
|
|||
|
|
if (unicoId) {
|
|||
|
|
versiones = getVersionesPlan(fecha, unicoId);
|
|||
|
|
const pedida = Number(sp.version) || undefined;
|
|||
|
|
foto = getPlanCerrado(fecha, unicoId, pedida) || (pedida ? getPlanCerrado(fecha, unicoId) : null);
|
|||
|
|
if (foto) comparacion = compararConFoto(foto.snapshot, actividades, plan, hoy);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
const puedeMarcar = Boolean(unicoId) && fecha >= hoy;
|
|||
|
|
const ultimaVersion = versiones.length ? versiones[versiones.length - 1] : null;
|
|||
|
|
// Resumen del equipo: quién ya marcó su plan ese día (por nombre de ejecutivo).
|
|||
|
|
const listos = verEquipo ? getPlanesListosDelDia(fecha) : {};
|
|||
|
|
const listoPorNombre = {};
|
|||
|
|
owners.forEach((o) => {
|
|||
|
|
if (listos[o.id]) listoPorNombre[o.name] = fmtMarca(listos[o.id].marcado_en).split(" ").slice(1).join(" ");
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
return (
|
|||
|
|
<div style={{ padding: 24 }}>
|
|||
|
|
<div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
|||
|
|
<h2>Plan del Día</h2>
|
|||
|
|
<div style={{ display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
|
|||
|
|
<Suspense fallback={null}>
|
|||
|
|
<PlanControles
|
|||
|
|
fecha={fecha}
|
|||
|
|
hoy={hoy}
|
|||
|
|
tituloPdf={tituloPdf}
|
|||
|
|
tituloPdfEquipo={`Plan del día – Resumen del equipo – ${fecha}`}
|
|||
|
|
conEquipo={verEquipo}
|
|||
|
|
/>
|
|||
|
|
</Suspense>
|
|||
|
|
<OwnerControl owners={owners} current={scope.locked ? [session.email] : scope.emails} locked={scope.locked} lockedLabel={session.email} />
|
|||
|
|
</div>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
{unicoId && (
|
|||
|
|
<PlanListoBoton
|
|||
|
|
fecha={fecha}
|
|||
|
|
ownerEmail={unicoEmail}
|
|||
|
|
nombre={unicoNombre}
|
|||
|
|
version={ultimaVersion?.version || null}
|
|||
|
|
marca={ultimaVersion ? fmtMarca(ultimaVersion.marcado_en) : ""}
|
|||
|
|
puedeMarcar={puedeMarcar}
|
|||
|
|
/>
|
|||
|
|
)}
|
|||
|
|
|
|||
|
|
{resumen && (
|
|||
|
|
<ResumenEquipo
|
|||
|
|
resumen={resumen}
|
|||
|
|
fecha={fecha}
|
|||
|
|
ventasTotal={suma(ventas)}
|
|||
|
|
renovTotal={suma(renovaciones)}
|
|||
|
|
listoPorNombre={listoPorNombre}
|
|||
|
|
/>
|
|||
|
|
)}
|
|||
|
|
|
|||
|
|
<div className="plan-doc plan-detalle">
|
|||
|
|
<h1 className="plan-titulo">PLAN DE ACTIVIDADES DEL DÍA</h1>
|
|||
|
|
<div className="plan-meta">
|
|||
|
|
<span><strong>Fecha:</strong> {fechaTxt(fecha)}</span>
|
|||
|
|
<span><strong>Ejecutivo:</strong> {quien}</span>
|
|||
|
|
{ultimaVersion && <span><strong>Plan listo:</strong> {fmtMarca(ultimaVersion.marcado_en)}</span>}
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div className="kpis plan-kpis">
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{money(suma(ventas))}</span>
|
|||
|
|
<span className="l">Ventas logradas del mes (al {fechaTxt(fecha)})</span>
|
|||
|
|
</div>
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{money(suma(renovaciones))}</span>
|
|||
|
|
<span className="l">Renovaciones logradas del mes (al {fechaTxt(fecha)})</span>
|
|||
|
|
</div>
|
|||
|
|
<div className="kpi">
|
|||
|
|
<span className="n">{plan.resumen.actHechas} de {plan.resumen.actTotal}</span>
|
|||
|
|
<span className="l">Actividades del día completadas</span>
|
|||
|
|
</div>
|
|||
|
|
<MrrSegmentos secciones={plan.secciones} nota="oportunidades con actividad este día" />
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
{plan.secciones.map((s) => (
|
|||
|
|
<PlanSeccion key={s.key} seccion={s} />
|
|||
|
|
))}
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
{foto && comparacion && (
|
|||
|
|
<PlanVsReal
|
|||
|
|
foto={foto}
|
|||
|
|
versiones={versiones}
|
|||
|
|
cmp={comparacion}
|
|||
|
|
nombre={unicoNombre}
|
|||
|
|
marca={fmtMarca(foto.marcado_en)}
|
|||
|
|
hrefVersion={(v) => {
|
|||
|
|
const p = new URLSearchParams();
|
|||
|
|
if (sp.owner) p.set("owner", sp.owner);
|
|||
|
|
if (sp.fecha) p.set("fecha", sp.fecha);
|
|||
|
|
p.set("version", String(v));
|
|||
|
|
return `/plan?${p.toString()}`;
|
|||
|
|
}}
|
|||
|
|
/>
|
|||
|
|
)}
|
|||
|
|
|
|||
|
|
<SinActividadPanel filas={sinActividad} titulo="Oportunidades sin actividad agendada este día" hint={`Cierre estimado entre el ${fechaTxt(lunes)} y el ${fechaTxt(domingo)} (semana de la fecha elegida) · solo en pantalla, no va en el PDF`} vacio="Todas las oportunidades con cierre esta semana tienen una actividad agendada este día." />
|
|||
|
|
</div>
|
|||
|
|
);
|
|||
|
|
}
|