Fase 4 (3/5): ¿Ya se agendó algo?, comparePanelMotivo en Renovaciones Perdidas, matriz de calor Nuevas Oportunidades
This commit is contained in:
commit
f8947c8a4d
75 changed files with 6347 additions and 0 deletions
10
.dockerignore
Normal file
10
.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
node_modules
|
||||||
|
.next
|
||||||
|
.git
|
||||||
|
data
|
||||||
|
__nm_old
|
||||||
|
.nm_trash*
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
8
.gitignore
vendored
Normal file
8
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
node_modules
|
||||||
|
.next
|
||||||
|
data
|
||||||
|
__nm_old
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
13
Dockerfile
Normal file
13
Dockerfile
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
FROM node:22-alpine
|
||||||
|
WORKDIR /app
|
||||||
|
# native modules on Alpine (musl) must be compiled
|
||||||
|
RUN apk add --no-cache python3 make g++
|
||||||
|
COPY package.json ./
|
||||||
|
RUN npm install
|
||||||
|
COPY . .
|
||||||
|
RUN npm run build
|
||||||
|
EXPOSE 3000
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV HOSTNAME=0.0.0.0
|
||||||
|
CMD ["npm", "start"]
|
||||||
4
app/actividades/loading.js
Normal file
4
app/actividades/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
46
app/actividades/page.js
Normal file
46
app/actividades/page.js
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getActividades, getSystemUsers } from "../lib/queries";
|
||||||
|
import { actAncla, actEstadoFinal, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import ActividadesClient from "../components/actividades/ActividadesClient";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function ActividadesPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
|
||||||
|
let raw, allUsers;
|
||||||
|
try {
|
||||||
|
[raw, allUsers] = await Promise.all([
|
||||||
|
getActividades(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
|
||||||
|
const actividades = raw
|
||||||
|
.filter((a) => a.estado !== "cancelada")
|
||||||
|
.map((a) => {
|
||||||
|
const ancla = actAncla(a);
|
||||||
|
return { ...a, fecha: ancla ? String(ancla).slice(0, 10) : null, estadoFinal: actEstadoFinal(a) };
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Plan de Actividades</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
<ActividadesClient actividades={actividades} locked={scope.locked} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
101
app/admin/metas/page.js
Normal file
101
app/admin/metas/page.js
Normal file
|
|
@ -0,0 +1,101 @@
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { auth } from "../../lib/auth";
|
||||||
|
import { getSystemUsers } from "../../lib/queries";
|
||||||
|
import { getMetas, getMetaGlobal, setMeta, setMetaGlobal } from "../../lib/metas";
|
||||||
|
import { EJECUTIVOS_VENTA } from "../../lib/derive";
|
||||||
|
import LoginPrompt from "../../components/LoginPrompt";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AdminMetasPage() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
if (!session.isAdmin) {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>Metas</h2>
|
||||||
|
<p>Esta página es solo para administradores.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allUsers = await getSystemUsers(session.accessToken);
|
||||||
|
const metas = getMetas();
|
||||||
|
const metaGlobal = getMetaGlobal();
|
||||||
|
|
||||||
|
const vendedoras = EJECUTIVOS_VENTA.map((nombre) => {
|
||||||
|
const u = allUsers.find((x) => x.name === nombre);
|
||||||
|
return { nombre, email: u?.email || null, monto: u ? metas[u.email] || 0 : 0 };
|
||||||
|
});
|
||||||
|
|
||||||
|
async function guardarMeta(formData) {
|
||||||
|
"use server";
|
||||||
|
const email = formData.get("email");
|
||||||
|
const monto = Number(formData.get("monto"));
|
||||||
|
if (email && monto >= 0) setMeta(email, monto);
|
||||||
|
revalidatePath("/admin/metas");
|
||||||
|
revalidatePath("/");
|
||||||
|
revalidatePath("/ganadas");
|
||||||
|
revalidatePath("/prevision");
|
||||||
|
revalidatePath("/tendencia");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function guardarGlobal(formData) {
|
||||||
|
"use server";
|
||||||
|
const monto = Number(formData.get("metaGlobal"));
|
||||||
|
if (monto >= 0) setMetaGlobal(monto);
|
||||||
|
revalidatePath("/admin/metas");
|
||||||
|
revalidatePath("/");
|
||||||
|
revalidatePath("/ganadas");
|
||||||
|
revalidatePath("/prevision");
|
||||||
|
revalidatePath("/tendencia");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>Metas mensuales</h2>
|
||||||
|
<p className="hint">
|
||||||
|
Solo administradores. Se guardan en SQLite (sobreviven a cada publicación, ver Etapa 4 en migration.md).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="panel" style={{ maxWidth: 420 }}>
|
||||||
|
<h3>Meta global del equipo</h3>
|
||||||
|
<form action={guardarGlobal} style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||||
|
<input name="metaGlobal" type="number" step="1" min="0" defaultValue={metaGlobal} style={{ width: 120 }} />
|
||||||
|
<button type="submit" className="login-btn">
|
||||||
|
Guardar
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ marginTop: 16, maxWidth: 520 }}>
|
||||||
|
<h3>Meta por ejecutiva</h3>
|
||||||
|
{vendedoras.map((v) => (
|
||||||
|
<div
|
||||||
|
key={v.nombre}
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
gap: 8,
|
||||||
|
alignItems: "center",
|
||||||
|
padding: "8px 0",
|
||||||
|
borderBottom: "1px solid var(--linea)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ width: 220, flexShrink: 0 }}>{v.nombre}</span>
|
||||||
|
{v.email ? (
|
||||||
|
<form action={guardarMeta} style={{ display: "flex", gap: 8, alignItems: "center" }}>
|
||||||
|
<input type="hidden" name="email" value={v.email} />
|
||||||
|
<input name="monto" type="number" step="1" min="0" defaultValue={v.monto} style={{ width: 100 }} />
|
||||||
|
<button type="submit" className="login-btn">
|
||||||
|
Guardar
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<span style={{ color: "var(--pierde)" }}>No encontrada en systemusers</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
app/agenda/page.js
Normal file
10
app/agenda/page.js
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
// Agenda pasó a ser la página de inicio ("/") — Marco pidió que sea lo primero que ve el equipo al
|
||||||
|
// entrar, en vez de Ventas Resumen. Esta ruta se conserva como redirect por si algún bookmark viejo
|
||||||
|
// apunta acá.
|
||||||
|
export default async function AgendaRedirect({ searchParams }) {
|
||||||
|
const params = new URLSearchParams(await searchParams);
|
||||||
|
const qs = params.toString();
|
||||||
|
redirect(qs ? `/?${qs}` : "/");
|
||||||
|
}
|
||||||
2
app/api/auth/[...nextauth]/route.js
Normal file
2
app/api/auth/[...nextauth]/route.js
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
import { handlers } from "../../../lib/auth";
|
||||||
|
export const { GET, POST } = handlers;
|
||||||
92
app/components/AppShell.js
Normal file
92
app/components/AppShell.js
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
"use client";
|
||||||
|
import { useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import Image from "next/image";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
|
||||||
|
export default function AppShell({ pages, session, onSignIn, onSignOut, children }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const pathname = usePathname();
|
||||||
|
const grupos = [...new Set(pages.map((p) => p.grupo))];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app">
|
||||||
|
<aside className={`side${open ? " open" : ""}`}>
|
||||||
|
<div className="side-logo">
|
||||||
|
<Image src="/assets/img/logo-alfa-blanco.png" alt="ALFA+" width={100} height={27} />
|
||||||
|
<div className="sub">Analítica Comercial</div>
|
||||||
|
</div>
|
||||||
|
<nav className="nav">
|
||||||
|
{grupos.map((g) => (
|
||||||
|
<div key={g}>
|
||||||
|
<div className="nav-grupo">{g}</div>
|
||||||
|
{pages
|
||||||
|
.filter((p) => p.grupo === g)
|
||||||
|
.map((p) =>
|
||||||
|
p.built ? (
|
||||||
|
<Link
|
||||||
|
key={p.href}
|
||||||
|
href={p.href}
|
||||||
|
className={`nav-item${pathname === p.href ? " active" : ""}`}
|
||||||
|
style={{ textDecoration: "none" }}
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
>
|
||||||
|
<span className="ico">{p.ico}</span>
|
||||||
|
{p.label}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<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>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="side-foot">
|
||||||
|
Datos: Dynamics 365
|
||||||
|
<br />
|
||||||
|
En vivo
|
||||||
|
</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>
|
||||||
|
<div className="ctrl" style={{ marginLeft: "auto" }}>
|
||||||
|
{session?.email ? (
|
||||||
|
<>
|
||||||
|
{session.isAdmin && (
|
||||||
|
<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">{children}</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
app/components/ErrorNotice.js
Normal file
17
app/components/ErrorNotice.js
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
export default function ErrorNotice({ error }) {
|
||||||
|
const isExpired = error?.message === "TOKEN_EXPIRED" || error?.message?.includes("RefreshFailed");
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>No se pudo cargar la información</h2>
|
||||||
|
{isExpired ? (
|
||||||
|
<p>Tu sesión con Dynamics expiró. Cerrá sesión y volvé a iniciarla.</p>
|
||||||
|
) : (
|
||||||
|
<p>
|
||||||
|
Dynamics no respondió correctamente (posiblemente por límite de consultas). Recargá la página en unos
|
||||||
|
segundos.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p style={{ color: "#9db4c9", fontSize: 12 }}>{error?.message}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
44
app/components/FilterChips.js
Normal file
44
app/components/FilterChips.js
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
"use client";
|
||||||
|
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||||
|
import { parseFiltParam, encodeFiltParam } from "../lib/filterState";
|
||||||
|
|
||||||
|
// Chips de filtros activos — equivalente a chips()/bindChips() del sitio HTML (assets/js/filters.js).
|
||||||
|
// dimLabels: {dimKey: "Etiqueta legible"} opcional, para no mostrar la clave técnica cruda.
|
||||||
|
export default function FilterChips({ dimLabels = {} }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const filt = parseFiltParam(searchParams.get("f"));
|
||||||
|
const keys = Object.keys(filt);
|
||||||
|
if (!keys.length) return null;
|
||||||
|
|
||||||
|
function removeDim(dim) {
|
||||||
|
const next = { ...filt };
|
||||||
|
delete next[dim];
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
const f = encodeFiltParam(next);
|
||||||
|
if (f) params.set("f", f);
|
||||||
|
else params.delete("f");
|
||||||
|
const qs = params.toString();
|
||||||
|
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAll() {
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
params.delete("f");
|
||||||
|
const qs = params.toString();
|
||||||
|
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="chips">
|
||||||
|
<span className="lbl">Filtros:</span>
|
||||||
|
{keys.map((k) => (
|
||||||
|
<span key={k} className="chip" onClick={() => removeDim(k)} title="Quitar filtro">
|
||||||
|
{dimLabels[k] || k}: {filt[k]} ✕
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
<span className="chip clear" onClick={clearAll}>Limpiar</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
31
app/components/FilterableRow.js
Normal file
31
app/components/FilterableRow.js
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
"use client";
|
||||||
|
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||||
|
import { parseFiltParam, encodeFiltParam, toggleFilt, isFiltActive } from "../lib/filterState";
|
||||||
|
|
||||||
|
// Envoltura clickeable genérica para clic-para-filtrar — reemplaza bindRows()/bindMatriz*() del
|
||||||
|
// sitio HTML (assets/js/filters.js). `pairs` es [[dim, valor], ...]: una fila de panel manda un
|
||||||
|
// solo par, una celda de matriz (calidad×movimiento, plan×termómetro) manda dos — el toggle es
|
||||||
|
// "todo o nada" sobre ese conjunto de ejes (ver toggleFilt en lib/filterState.js).
|
||||||
|
export default function FilterableRow({ pairs, className = "", activeClassName = "active", as: As = "div", children, ...rest }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const filt = parseFiltParam(searchParams.get("f"));
|
||||||
|
const active = isFiltActive(filt, pairs);
|
||||||
|
|
||||||
|
function onClick() {
|
||||||
|
const next = toggleFilt(filt, pairs);
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
const f = encodeFiltParam(next);
|
||||||
|
if (f) params.set("f", f);
|
||||||
|
else params.delete("f");
|
||||||
|
const qs = params.toString();
|
||||||
|
router.push(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<As className={`${className} ${active ? activeClassName : ""}`.trim()} onClick={onClick} {...rest}>
|
||||||
|
{children}
|
||||||
|
</As>
|
||||||
|
);
|
||||||
|
}
|
||||||
8
app/components/LoginPrompt.js
Normal file
8
app/components/LoginPrompt.js
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
export default function LoginPrompt() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 40, textAlign: "center" }}>
|
||||||
|
<h2>Informe Comercial ALFA+</h2>
|
||||||
|
<p>Iniciá sesión con tu cuenta de Alfanumeric para ver tu información.</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
41
app/components/OwnerControl.js
Normal file
41
app/components/OwnerControl.js
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
"use client";
|
||||||
|
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||||
|
|
||||||
|
export default function OwnerControl({ owners, current, locked, lockedLabel }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
if (locked) {
|
||||||
|
return (
|
||||||
|
<div className="ctrl owner-ctrl">
|
||||||
|
<label>Propietario</label>
|
||||||
|
<button type="button" className="owner-btn" disabled>
|
||||||
|
{lockedLabel}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onChange(e) {
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
if (e.target.value) params.set("owner", e.target.value);
|
||||||
|
else params.delete("owner");
|
||||||
|
const qs = params.toString();
|
||||||
|
router.push(qs ? `${pathname}?${qs}` : pathname);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ctrl owner-ctrl">
|
||||||
|
<label>Propietario</label>
|
||||||
|
<select value={current || ""} onChange={onChange}>
|
||||||
|
<option value="">Todos los propietarios</option>
|
||||||
|
{owners.map((o) => (
|
||||||
|
<option key={o.id} value={o.email}>
|
||||||
|
{o.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
17
app/components/PageLoading.js
Normal file
17
app/components/PageLoading.js
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
// Fallback de carga — Next.js la muestra automáticamente (vía loading.js) mientras la página de
|
||||||
|
// datos espera Dynamics, en vez de dejar la pantalla en blanco. El armazón (nav, topbar) ya está
|
||||||
|
// pintado en este punto porque vive en layout.js, fuera de este límite de Suspense.
|
||||||
|
export default function PageLoading() {
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div className="kpis">
|
||||||
|
{[0, 1, 2, 3].map((i) => (
|
||||||
|
<div className="kpi" key={i} style={{ opacity: 0.5 }}>
|
||||||
|
<span className="n">···</span>
|
||||||
|
<span className="l">Cargando…</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
24
app/components/PlanFilterSelect.js
Normal file
24
app/components/PlanFilterSelect.js
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
"use client";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
// Select "Plan de Cierre" de Detalle — navega por URL (?plan=...) al cambiar, mismo patrón que el
|
||||||
|
// resto de la app (sin estado de cliente propio, todo vive en la URL).
|
||||||
|
export default function PlanFilterSelect({ options, current, baseHref }) {
|
||||||
|
const router = useRouter();
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
value={current || ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
const url = new URL(baseHref, "http://x");
|
||||||
|
if (e.target.value) url.searchParams.set("plan", e.target.value);
|
||||||
|
else url.searchParams.delete("plan");
|
||||||
|
router.push(url.pathname + url.search);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Todos los planes</option>
|
||||||
|
{options.map((p) => (
|
||||||
|
<option key={p} value={p}>{p}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
28
app/components/SegTabs.js
Normal file
28
app/components/SegTabs.js
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
"use client";
|
||||||
|
import { useRouter, useSearchParams, usePathname } from "next/navigation";
|
||||||
|
|
||||||
|
// Pestañas rotativas genéricas — reemplaza indTabsBar()/las pestañas de MTZ_DIMS/COH_DIMS del
|
||||||
|
// sitio HTML (assets/js/tables.js). `tabs` es [{k, lbl}], `paramName` el searchParam que guarda la
|
||||||
|
// pestaña activa (equivalente a indTab/mtzEjeDim/cohDim en state.js — acá vive en la URL, no en
|
||||||
|
// una variable global de módulo).
|
||||||
|
export default function SegTabs({ tabs, activeKey, paramName }) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
|
||||||
|
function onClick(k) {
|
||||||
|
const params = new URLSearchParams(searchParams.toString());
|
||||||
|
params.set(paramName, k);
|
||||||
|
router.push(`${pathname}?${params.toString()}`, { scroll: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="seg-tabs">
|
||||||
|
{tabs.map((t) => (
|
||||||
|
<button key={t.k} type="button" className={t.k === activeKey ? "on" : ""} onClick={() => onClick(t.k)}>
|
||||||
|
{t.lbl}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
181
app/components/actividades/ActividadesClient.js
Normal file
181
app/components/actividades/ActividadesClient.js
Normal file
|
|
@ -0,0 +1,181 @@
|
||||||
|
"use client";
|
||||||
|
import { useState, useMemo } from "react";
|
||||||
|
import { agg, aggOrd, ETAPA_ORDER, EJECUTIVOS_VENTA } from "../../lib/derive";
|
||||||
|
import { actividadUrl } from "../../lib/constants";
|
||||||
|
import Panel from "../pipeline/Panel";
|
||||||
|
|
||||||
|
const HORIZONTES = [
|
||||||
|
["hoy", "Hoy"], ["semana", "Esta semana"], ["semana_pasada", "Semana pasada"],
|
||||||
|
["mes", "Este mes"], ["mes_pasado", "Mes pasado"], ["todas", "Todas"],
|
||||||
|
];
|
||||||
|
|
||||||
|
function inicioSemana(d) {
|
||||||
|
const x = new Date(d);
|
||||||
|
const dow = (x.getDay() + 6) % 7;
|
||||||
|
x.setDate(x.getDate() - dow);
|
||||||
|
x.setHours(0, 0, 0, 0);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
function enRango(fecha, horizonte) {
|
||||||
|
if (horizonte === "todas") return true;
|
||||||
|
if (!fecha) return false;
|
||||||
|
const f = new Date(fecha);
|
||||||
|
f.setHours(0, 0, 0, 0);
|
||||||
|
const hoy = new Date();
|
||||||
|
hoy.setHours(0, 0, 0, 0);
|
||||||
|
if (horizonte === "hoy") return f.getTime() === hoy.getTime();
|
||||||
|
if (horizonte === "semana" || horizonte === "semana_pasada") {
|
||||||
|
const lunes = inicioSemana(hoy);
|
||||||
|
if (horizonte === "semana_pasada") lunes.setDate(lunes.getDate() - 7);
|
||||||
|
const domingo = new Date(lunes);
|
||||||
|
domingo.setDate(lunes.getDate() + (horizonte === "semana" ? 6 : 6));
|
||||||
|
if (horizonte === "semana_pasada") domingo.setDate(lunes.getDate() + 6);
|
||||||
|
return f >= lunes && f <= domingo;
|
||||||
|
}
|
||||||
|
if (horizonte === "mes" || horizonte === "mes_pasado") {
|
||||||
|
const base = new Date(hoy.getFullYear(), hoy.getMonth() - (horizonte === "mes_pasado" ? 1 : 0), 1);
|
||||||
|
return f.getFullYear() === base.getFullYear() && f.getMonth() === base.getMonth();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TablaTipo({ titulo, rows, locked }) {
|
||||||
|
if (!rows.length) return null;
|
||||||
|
return (
|
||||||
|
<div className="panel" style={{ marginBottom: 14 }}>
|
||||||
|
<h3>{titulo} — {rows.length}</h3>
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Asunto</th><th>Referente</th><th>Objetivo</th>
|
||||||
|
{!locked && <th>Ejecutivo</th>}
|
||||||
|
<th>Estado</th><th>Fecha</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((a) => (
|
||||||
|
<tr key={a.id}>
|
||||||
|
<td><a className="opp" href={actividadUrl(a)} target="_blank" rel="noopener">{a.asunto}</a></td>
|
||||||
|
<td>{a.referente?.nombre || "—"}</td>
|
||||||
|
<td>{a.objetivo || "—"}</td>
|
||||||
|
{!locked && <td>{a.owner}</td>}
|
||||||
|
<td>
|
||||||
|
<span className={a.estadoFinal === "Vencida" ? "pierde" : a.estadoFinal === "Completada" ? "gana" : ""}>
|
||||||
|
{a.estadoFinal}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>{a.scheduledendFmt || a.scheduledstartFmt || "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ActividadesClient({ actividades, locked }) {
|
||||||
|
const [horizonte, setHorizonte] = useState("mes");
|
||||||
|
|
||||||
|
const filtradas = useMemo(
|
||||||
|
() => actividades.filter((a) => enRango(a.fecha, horizonte)),
|
||||||
|
[actividades, horizonte]
|
||||||
|
);
|
||||||
|
|
||||||
|
const completadas = filtradas.filter((a) => a.estadoFinal === "Completada");
|
||||||
|
const vencidas = filtradas.filter((a) => a.estadoFinal === "Vencida");
|
||||||
|
const pendientes = filtradas.filter((a) => a.estadoFinal === "Pendiente");
|
||||||
|
const cumplimiento = filtradas.length ? Math.round((completadas.length / filtradas.length) * 100) : 0;
|
||||||
|
const conObjetivo = filtradas.filter((a) => a.objetivo).length;
|
||||||
|
const conOportunidad = filtradas.filter((a) => a.referente?.tipo === "opportunity");
|
||||||
|
|
||||||
|
const porEjecutivo = EJECUTIVOS_VENTA.map((nombre) => {
|
||||||
|
const propias = filtradas.filter((a) => a.owner === nombre);
|
||||||
|
const hechas = propias.filter((a) => a.estadoFinal === "Completada").length;
|
||||||
|
const pct = propias.length ? Math.round((hechas / propias.length) * 100) : null;
|
||||||
|
return { nombre, total: propias.length, hechas, pct };
|
||||||
|
}).sort((a, b) => (b.pct ?? -1) - (a.pct ?? -1));
|
||||||
|
|
||||||
|
// Oportunidades relacionadas — actividades que sí traen Ingreso Estimado/Tipo de Oportunidad
|
||||||
|
// vía $expand, agrupadas por la oportunidad referida.
|
||||||
|
const porOportunidad = new Map();
|
||||||
|
conOportunidad.forEach((a) => {
|
||||||
|
const k = a.referente.id;
|
||||||
|
if (!porOportunidad.has(k)) {
|
||||||
|
porOportunidad.set(k, { nombre: a.referente.nombre, tipo: a.tipoOportunidad, est: a.ingresoEstimado || 0, n: 0 });
|
||||||
|
}
|
||||||
|
porOportunidad.get(k).n++;
|
||||||
|
});
|
||||||
|
const oportunidadesRelacionadas = [...porOportunidad.values()].sort((a, b) => b.n - a.n).slice(0, 12);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<p className="hint" style={{ marginBottom: 8 }}>
|
||||||
|
No hay seguimiento registrado en el CRM ≠ no hubo seguimiento — la mayoría del contacto comercial se hace por
|
||||||
|
WhatsApp, que no está integrado a Dynamics (ver CLAUDE.md). Ventana de datos: últimos 90 días cerrados + todo
|
||||||
|
lo que sigue abierto.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||||
|
{HORIZONTES.map(([k, l]) => (
|
||||||
|
<button key={k} className={horizonte === k ? "on" : ""} type="button" onClick={() => setHorizonte(k)}>{l}</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{filtradas.length}</span><span className="l">Actividades (sin canceladas)</span></div>
|
||||||
|
<div className="kpi"><span className="n">{cumplimiento}%</span><span className="l">Cumplimiento (completadas/total)</span></div>
|
||||||
|
<div className="kpi"><span className="n">{pendientes.length}</span><span className="l">Pendientes</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{vencidas.length}</span><span className="l">Vencidas</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="hint">
|
||||||
|
Con Objetivo de Actividad asignado: <b>{conObjetivo}</b> ({filtradas.length ? Math.round((conObjetivo / filtradas.length) * 100) : 0}%) —
|
||||||
|
adopción real del campo. Referidas a Oportunidad: <b>{conOportunidad.length}</b> ({filtradas.length ? Math.round((conOportunidad.length / filtradas.length) * 100) : 0}%).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="grid2" style={{ marginTop: 18 }}>
|
||||||
|
<Panel title="Por Etapa" rows={aggOrd(filtradas, "etapa", ETAPA_ORDER)} hideMoney />
|
||||||
|
<Panel title="Por Tipo de Actividad" rows={agg(filtradas, "tipo")} hideMoney />
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Cumplimiento por ejecutivo</h3>
|
||||||
|
<p className="hint">Completadas ÷ total de actividades (sin canceladas) de cada quien</p>
|
||||||
|
{porEjecutivo.map((r) => (
|
||||||
|
<div className="row static" key={r.nombre}>
|
||||||
|
<div className="bl"><span className="nm">{r.nombre}</span></div>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div
|
||||||
|
className={`bar-fill ${r.pct == null ? "" : r.pct >= 70 ? "" : r.pct >= 50 ? "alerta" : "pierde"}`}
|
||||||
|
style={{ width: `${Math.min(100, r.pct ?? 0)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="v">{r.pct == null ? "n/d" : `${r.pct}%`}</span>
|
||||||
|
<span className="c">{r.hechas}/{r.total}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Oportunidades relacionadas</h3>
|
||||||
|
<p className="hint">Oportunidades con más actividades referidas en este período</p>
|
||||||
|
{oportunidadesRelacionadas.length ? oportunidadesRelacionadas.map((o) => (
|
||||||
|
<div className="row static" key={o.nombre}>
|
||||||
|
<div className="bl"><span className="nm">{o.nombre}</span></div>
|
||||||
|
<div className="bar-cell" />
|
||||||
|
<span className="v">{o.n} act.</span>
|
||||||
|
<span className="c">{o.tipo || "—"}</span>
|
||||||
|
</div>
|
||||||
|
)) : <p className="hint">Ninguna actividad de este período está referida a una Oportunidad.</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="sec-div"><span>Detalle</span></div>
|
||||||
|
<TablaTipo titulo="Citas" rows={filtradas.filter((a) => a.tipo === "Cita")} locked={locked} />
|
||||||
|
<TablaTipo titulo="Llamadas" rows={filtradas.filter((a) => a.tipo === "Llamada")} locked={locked} />
|
||||||
|
<TablaTipo titulo="Tareas" rows={filtradas.filter((a) => a.tipo === "Tarea")} locked={locked} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
250
app/components/agenda/AgendaClient.js
Normal file
250
app/components/agenda/AgendaClient.js
Normal file
|
|
@ -0,0 +1,250 @@
|
||||||
|
"use client";
|
||||||
|
import { useState, useMemo } from "react";
|
||||||
|
import { actAncla, actEstadoFinal } from "../../lib/derive";
|
||||||
|
import { actividadUrl } from "../../lib/constants";
|
||||||
|
|
||||||
|
const AG_DIAS = ["Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"];
|
||||||
|
const AG_MESES = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"];
|
||||||
|
const AG_MESES_LARGO = [
|
||||||
|
"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre",
|
||||||
|
];
|
||||||
|
|
||||||
|
const pad = (n) => (n < 10 ? "0" + n : "" + n);
|
||||||
|
const iso = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||||
|
const hoyISO = () => iso(new Date());
|
||||||
|
// Semana Lunes-Domingo, igual que el resto del informe.
|
||||||
|
function inicioSemana(d) {
|
||||||
|
const x = new Date(d);
|
||||||
|
const dow = (x.getDay() + 6) % 7;
|
||||||
|
x.setDate(x.getDate() - dow);
|
||||||
|
x.setHours(0, 0, 0, 0);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
function fechaISO(a) {
|
||||||
|
const f = actAncla(a);
|
||||||
|
return f ? String(f).slice(0, 10) : null;
|
||||||
|
}
|
||||||
|
function diasParaVencer(a) {
|
||||||
|
const f = fechaISO(a);
|
||||||
|
if (!f) return null;
|
||||||
|
const d = new Date(f + "T12:00:00");
|
||||||
|
const hoy = new Date();
|
||||||
|
hoy.setHours(12, 0, 0, 0);
|
||||||
|
return Math.round((d - hoy) / 86400000);
|
||||||
|
}
|
||||||
|
function fechaTxt(f) {
|
||||||
|
if (!f) return "—";
|
||||||
|
const [y, m, d] = f.split("-");
|
||||||
|
return `${d}/${m}/${y}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Item({ a }) {
|
||||||
|
const venc = a.estadoFinal === "Vencida";
|
||||||
|
const hecha = a.estadoFinal === "Completada";
|
||||||
|
const ref = a.referente && a.referente.nombre ? a.referente.nombre : a.asunto || "—";
|
||||||
|
const sub = [a.owner.split(" ").slice(0, 2).join(" ")];
|
||||||
|
if (venc) sub.push(`vencida hace ${Math.abs(a.dv)} día${Math.abs(a.dv) === 1 ? "" : "s"}`);
|
||||||
|
if (hecha) sub.push("completada");
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
className={`ag-item t-${a.tipo.toLowerCase()}${venc ? " venc" : ""}${hecha ? " hecha" : ""}`}
|
||||||
|
href={actividadUrl(a)}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener"
|
||||||
|
title={a.asunto || ""}
|
||||||
|
>
|
||||||
|
<span className="ag-item-t">{a.tipo} · {ref}</span>
|
||||||
|
<span className="ag-item-s">{sub.join(" · ")}</span>
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AgendaClient({ actividades }) {
|
||||||
|
const [vista, setVista] = useState("semana");
|
||||||
|
const [ancla, setAncla] = useState(() => new Date());
|
||||||
|
const [tipos, setTipos] = useState(new Set(["Cita", "Llamada", "Tarea"]));
|
||||||
|
const [verHechas, setVerHechas] = useState(false);
|
||||||
|
const [diaSel, setDiaSel] = useState(null);
|
||||||
|
|
||||||
|
const list = useMemo(() => {
|
||||||
|
return actividades
|
||||||
|
.filter((a) => tipos.has(a.tipo) && a.estado !== "cancelada" && fechaISO(a))
|
||||||
|
.map((a) => ({ ...a, fecha: fechaISO(a), dv: diasParaVencer(a), estadoFinal: actEstadoFinal(a) }))
|
||||||
|
.filter((a) => verHechas || a.estadoFinal !== "Completada");
|
||||||
|
}, [actividades, tipos, verHechas]);
|
||||||
|
|
||||||
|
const lunesHoy = inicioSemana(new Date());
|
||||||
|
const domingoHoy = new Date(lunesHoy);
|
||||||
|
domingoHoy.setDate(lunesHoy.getDate() + 6);
|
||||||
|
const estaSem = list.filter((a) => a.fecha >= iso(lunesHoy) && a.fecha <= iso(domingoHoy)).length;
|
||||||
|
const venc = list.filter((a) => a.estadoFinal === "Vencida").length;
|
||||||
|
const pend = list.filter((a) => a.estadoFinal === "Pendiente").length;
|
||||||
|
|
||||||
|
const toggleTipo = (t) => {
|
||||||
|
setTipos((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(t)) next.delete(t); else next.add(t);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const cursor = vista === "mes" ? new Date(ancla.getFullYear(), ancla.getMonth(), 1) : ancla;
|
||||||
|
|
||||||
|
const mover = (d) => {
|
||||||
|
setDiaSel(null);
|
||||||
|
setAncla((prev) => {
|
||||||
|
const next = new Date(prev);
|
||||||
|
if (vista === "semana") next.setDate(next.getDate() + d * 7);
|
||||||
|
else next.setMonth(next.getMonth() + d);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let cuerpo, lbl;
|
||||||
|
if (vista === "semana") {
|
||||||
|
const lunes = inicioSemana(cursor);
|
||||||
|
const dias = Array.from({ length: 7 }, (_, i) => {
|
||||||
|
const d = new Date(lunes);
|
||||||
|
d.setDate(lunes.getDate() + i);
|
||||||
|
return d;
|
||||||
|
});
|
||||||
|
lbl = `${dias[0].getDate()} ${AG_MESES[dias[0].getMonth()]} – ${dias[6].getDate()} ${AG_MESES[dias[6].getMonth()]} ${dias[6].getFullYear()}`;
|
||||||
|
const hoy = hoyISO();
|
||||||
|
cuerpo = (
|
||||||
|
<div className="ag-week">
|
||||||
|
{dias.map((d, i) => {
|
||||||
|
const diso = iso(d);
|
||||||
|
const items = list
|
||||||
|
.filter((a) => a.fecha === diso)
|
||||||
|
.sort((a, b) => (a.referente?.nombre || "").localeCompare(b.referente?.nombre || ""));
|
||||||
|
return (
|
||||||
|
<div className={`ag-day${diso === hoy ? " hoy" : ""}`} key={diso}>
|
||||||
|
<div className="ag-day-h">
|
||||||
|
<span>{AG_DIAS[i]}</span>
|
||||||
|
<span>{d.getDate()} {AG_MESES[d.getMonth()]}</span>
|
||||||
|
</div>
|
||||||
|
{items.length ? items.map((a) => <Item a={a} key={a.id} />) : <span className="ag-vacio">Sin actividades</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
} else if (vista === "mes") {
|
||||||
|
const inicio = inicioSemana(new Date(cursor.getFullYear(), cursor.getMonth(), 1));
|
||||||
|
const celdas = Array.from({ length: 42 }, (_, i) => {
|
||||||
|
const d = new Date(inicio);
|
||||||
|
d.setDate(inicio.getDate() + i);
|
||||||
|
return d;
|
||||||
|
});
|
||||||
|
const hoy = hoyISO();
|
||||||
|
lbl = `${AG_MESES_LARGO[cursor.getMonth()]} ${cursor.getFullYear()}`;
|
||||||
|
const sel = diaSel ? list.filter((a) => a.fecha === diaSel) : [];
|
||||||
|
cuerpo = (
|
||||||
|
<>
|
||||||
|
<div className="ag-month">
|
||||||
|
{AG_DIAS.map((n) => <div className="ag-m-h" key={n}>{n}</div>)}
|
||||||
|
{celdas.map((d) => {
|
||||||
|
const diso = iso(d);
|
||||||
|
const items = list.filter((a) => a.fecha === diso);
|
||||||
|
const hayVenc = items.some((a) => a.estadoFinal === "Vencida");
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`ag-m-d${d.getMonth() !== cursor.getMonth() ? " otro" : ""}${diso === hoy ? " hoy" : ""}${diso === diaSel ? " sel" : ""}`}
|
||||||
|
key={diso}
|
||||||
|
onClick={() => setDiaSel(diso === diaSel ? null : diso)}
|
||||||
|
style={{ cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
<span className="ag-m-num">{d.getDate()}</span>
|
||||||
|
{items.length > 0 && <span className={`ag-m-badge${hayVenc ? " venc" : ""}`}>{items.length}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{diaSel && (
|
||||||
|
<div className="panel" style={{ marginTop: 14, marginBottom: 0 }}>
|
||||||
|
<h3>{fechaTxt(diaSel)}</h3>
|
||||||
|
{sel.length ? (
|
||||||
|
<div className="ag-lista">{sel.map((a) => <Item a={a} key={a.id} />)}</div>
|
||||||
|
) : (
|
||||||
|
<p className="hint" style={{ margin: 0 }}>Sin actividades este día.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const v = list.filter((a) => a.estadoFinal === "Vencida").sort((a, b) => a.dv - b.dv);
|
||||||
|
const masViejo = v.length ? Math.abs(v[0].dv) : 0;
|
||||||
|
lbl = `${v.length} vencida${v.length === 1 ? "" : "s"}`;
|
||||||
|
cuerpo = (
|
||||||
|
<div className="panel" style={{ marginBottom: 0 }}>
|
||||||
|
<h3>Vencidas — de la más atrasada a la más reciente</h3>
|
||||||
|
{v.length ? (
|
||||||
|
<>
|
||||||
|
<p className="hint">{v.length} actividades planificadas cuya fecha ya pasó y siguen abiertas · la más antigua lleva {masViejo} días</p>
|
||||||
|
<div className="ag-lista scroll">{v.map((a) => <Item a={a} key={a.id} />)}</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="hint" style={{ margin: 0 }}>No hay actividades vencidas con este filtro.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<p className="hint" style={{ margin: "-4px 0 14px" }}>
|
||||||
|
Solo lectura: muestra lo que ya está planificado en Dynamics. Clic en una actividad la abre en Dynamics.
|
||||||
|
</p>
|
||||||
|
<div className="panel" style={{ display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap", padding: "12px 18px" }}>
|
||||||
|
<div>
|
||||||
|
<span className="ag-f-lbl">Tipo de actividad</span>
|
||||||
|
<div className="ag-tipos">
|
||||||
|
{["Cita", "Llamada", "Tarea"].map((t) => (
|
||||||
|
<label className="ag-tipo" key={t}>
|
||||||
|
<input type="checkbox" checked={tipos.has(t)} onChange={() => toggleTipo(t)} /> {t}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="ag-f-lbl">Estado</span>
|
||||||
|
<div className="ag-tipos">
|
||||||
|
<label className="ag-tipo">
|
||||||
|
<input type="checkbox" checked={verHechas} onChange={(e) => setVerHechas(e.target.checked)} /> Mostrar completadas
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style={{ marginLeft: "auto", fontSize: 11.5, color: "var(--tinta-suave)" }}>
|
||||||
|
Se excluyen las canceladas
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{list.length}</span><span className="l">Actividades con el filtro actual</span></div>
|
||||||
|
<div className="kpi"><span className="n">{estaSem}</span><span className="l">Esta semana (lun a dom)</span></div>
|
||||||
|
<div className="kpi"><span className="n">{pend}</span><span className="l">Pendientes por delante</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{venc}</span><span className="l">Vencidas — su fecha ya pasó</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ag-toolbar">
|
||||||
|
<div className="seg-tabs">
|
||||||
|
{[["semana", "Semana"], ["mes", "Mes"], ["vencidas", "Vencidas"]].map(([k, l]) => (
|
||||||
|
<button key={k} className={vista === k ? "on" : ""} type="button" onClick={() => { setVista(k); setDiaSel(null); }}>
|
||||||
|
{l}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{vista !== "vencidas" && (
|
||||||
|
<div className="ag-nav">
|
||||||
|
<button className="ag-nav-b" type="button" aria-label="Anterior" onClick={() => mover(-1)}>←</button>
|
||||||
|
<span className="ag-nav-lbl">{lbl}</span>
|
||||||
|
<button className="ag-nav-b" type="button" aria-label="Siguiente" onClick={() => mover(1)}>→</button>
|
||||||
|
<button className="ag-nav-b" type="button" onClick={() => { setAncla(new Date()); setDiaSel(null); }}>Hoy</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{cuerpo}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
99
app/components/nuevas/CohMatriz.js
Normal file
99
app/components/nuevas/CohMatriz.js
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
import React from "react";
|
||||||
|
import FilterableRow from "../FilterableRow";
|
||||||
|
import SegTabs from "../SegTabs";
|
||||||
|
|
||||||
|
// Matriz de calor dimensión × mes de creación — puerto de cohMatriz()/cohHeat()
|
||||||
|
// (App Informe/assets/js/pages/nuevas.js). `dims`/`metricas` traen `calc`/`fmt` (y `rgb` para el
|
||||||
|
// color); el heat se computa acá mismo contra el máximo de la tabla completa.
|
||||||
|
export default function CohMatriz({ arr, meses, dims, metricas, activeDimKey, activeMetKey, mesLbl }) {
|
||||||
|
const dim = dims.find((d) => d.k === activeDimKey) || dims[0];
|
||||||
|
const met = metricas.find((m) => m.k === activeMetKey) || metricas[0];
|
||||||
|
|
||||||
|
const cats = [...new Set(arr.map((o) => o[dim.k] || "(sin dato)"))]
|
||||||
|
.map((k) => ({ k, n: arr.filter((o) => (o[dim.k] || "(sin dato)") === k).length }))
|
||||||
|
.sort((a, b) => b.n - a.n)
|
||||||
|
.slice(0, 14);
|
||||||
|
const cel = (k, m) => arr.filter((o) => (o[dim.k] || "(sin dato)") === k && o.mesCohorte === m);
|
||||||
|
const valores = cats.flatMap((c) => meses.map((m) => met.calc(cel(c.k, m)))).filter((v) => v != null);
|
||||||
|
const max = Math.max(...valores, 0);
|
||||||
|
|
||||||
|
function heat(v) {
|
||||||
|
if (v == null) return { bg: "", fg: "var(--tinta-suave)" };
|
||||||
|
const r = max > 0 ? Math.max(0, v) / max : 0;
|
||||||
|
const a = v === 0 ? 0 : 0.06 + 0.74 * r;
|
||||||
|
return { bg: a ? `rgba(${met.rgb},${a.toFixed(2)})` : "", fg: a > 0.48 ? "#fff" : "var(--tinta)" };
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Matriz de calor — {dim.lbl} × mes de creación</h3>
|
||||||
|
<p className="hint">
|
||||||
|
La intensidad del color es el valor de la celda dentro de esta tabla · clic en una fila o celda filtra por
|
||||||
|
esa categoría · solo se muestran las 14 categorías con más volumen creado
|
||||||
|
</p>
|
||||||
|
<p className="hint" style={{ marginTop: -6 }}>
|
||||||
|
⚠ Un 100% sobre 2 oportunidades pinta igual de intenso que uno sobre 40 — pasá el cursor por la celda para
|
||||||
|
ver el conteo real antes de sacar conclusiones.
|
||||||
|
</p>
|
||||||
|
<div style={{ marginBottom: 8 }}>
|
||||||
|
<SegTabs tabs={dims.map((d) => ({ k: d.k, lbl: d.lbl }))} activeKey={dim.k} paramName="cohd" />
|
||||||
|
</div>
|
||||||
|
<div style={{ marginBottom: 12 }}>
|
||||||
|
<SegTabs tabs={metricas.map((m) => ({ k: m.k, lbl: m.lbl }))} activeKey={met.k} paramName="cohm" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mze"
|
||||||
|
style={{ gridTemplateColumns: `minmax(130px,1.5fr) repeat(${meses.length},minmax(56px,1fr)) minmax(70px,.85fr)` }}
|
||||||
|
>
|
||||||
|
<div className="mze-h eje" />
|
||||||
|
{meses.map((m) => <div className="mze-h" key={m}>{mesLbl(m).slice(0, 3)}</div>)}
|
||||||
|
<div className="mze-h tot">Total</div>
|
||||||
|
{cats.map((c) => {
|
||||||
|
const totA = arr.filter((o) => (o[dim.k] || "(sin dato)") === c.k);
|
||||||
|
return (
|
||||||
|
<React.Fragment key={c.k}>
|
||||||
|
<FilterableRow as="div" pairs={[[dim.k, c.k]]} className="mze-r" title={`Ver solo ${c.k}`}>
|
||||||
|
{c.k}
|
||||||
|
</FilterableRow>
|
||||||
|
{meses.map((m) => {
|
||||||
|
const a = cel(c.k, m);
|
||||||
|
const v = met.calc(a);
|
||||||
|
const h = heat(v);
|
||||||
|
return (
|
||||||
|
<FilterableRow
|
||||||
|
as="div"
|
||||||
|
key={`${c.k}-${m}`}
|
||||||
|
pairs={[[dim.k, c.k]]}
|
||||||
|
className={`mze-c${a.length ? "" : " vacia"}`}
|
||||||
|
style={{ background: h.bg, color: h.fg }}
|
||||||
|
title={`${c.k} · ${mesLbl(m)} — ${a.length} creada(s), ${a.filter((o) => o.estado === "Ganada").length} ganada(s), ${a.filter((o) => o.estado === "Perdida").length} perdida(s), ${a.filter((o) => o.estado === "Abierta").length} abierta(s)`}
|
||||||
|
>
|
||||||
|
<span className="n">{met.fmt(v)}</span>
|
||||||
|
</FilterableRow>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-c tot">
|
||||||
|
<span className="n">{met.fmt(met.calc(totA))}</span>
|
||||||
|
<span className="v">{totA.length} creadas</span>
|
||||||
|
</div>
|
||||||
|
</React.Fragment>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-r tot">Total</div>
|
||||||
|
{meses.map((m) => {
|
||||||
|
const a = arr.filter((o) => o.mesCohorte === m);
|
||||||
|
return (
|
||||||
|
<div className="mze-c tot" key={`pie-${m}`}>
|
||||||
|
<span className="n">{met.fmt(met.calc(a))}</span>
|
||||||
|
<span className="v">{a.length}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-c tot">
|
||||||
|
<span className="n">{met.fmt(met.calc(arr))}</span>
|
||||||
|
<span className="v">{arr.length}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
56
app/components/pipeline/ComparePanelMotivo.js
Normal file
56
app/components/pipeline/ComparePanelMotivo.js
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
|
||||||
|
// Barras Gana/Pierde apiladas por categoría + motivo de pérdida más frecuente — puerto de
|
||||||
|
// comparePanelMotivo() (App Informe/assets/js/tables.js). `cats` viene de catsWonLost() (derive.js).
|
||||||
|
export default function ComparePanelMotivo({ title, hint, cats }) {
|
||||||
|
const max = Math.max(...cats.flatMap((c) => [c.ganaV, c.pierdeV]), 0.1);
|
||||||
|
const fmtV = (v) => (v < 20 ? `$${v.toFixed(2)}` : money(v));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="panel">
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<p className="hint">{hint}</p>
|
||||||
|
{cats.length === 0 ? (
|
||||||
|
<p className="hint">Sin datos en este período.</p>
|
||||||
|
) : (
|
||||||
|
cats.map((c) => (
|
||||||
|
<div key={c.k} style={{ padding: "7px 4px", borderBottom: "1px solid var(--linea)" }}>
|
||||||
|
<div style={{ fontSize: 12.5, marginBottom: 5, fontWeight: 700 }}>{c.k}</div>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
|
||||||
|
<span style={{ fontSize: 10, color: "var(--gana)", width: 52 }}>Gana</span>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div className="bar-fill" style={{ width: `${((c.ganaV / max) * 100).toFixed(1)}%` }} />
|
||||||
|
</div>
|
||||||
|
<span className="v">
|
||||||
|
{fmtV(c.ganaV)}
|
||||||
|
<span style={{ color: "var(--tinta-suave)" }}> ({c.ganaN})</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||||
|
<span style={{ fontSize: 10, color: "var(--pierde)", width: 52 }}>Pierde</span>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div className="bar-fill pierde" style={{ width: `${((c.pierdeV / max) * 100).toFixed(1)}%` }} />
|
||||||
|
</div>
|
||||||
|
<span className="v">
|
||||||
|
{fmtV(c.pierdeV)}
|
||||||
|
<span style={{ color: "var(--tinta-suave)" }}> ({c.pierdeN})</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{(c.topMotivo || c.depu > 0) && (
|
||||||
|
<p className="hint" style={{ margin: "4px 0 0" }}>
|
||||||
|
{c.topMotivo ? (
|
||||||
|
<>
|
||||||
|
Motivo principal de pérdida: <b>{c.topMotivo}</b> ({c.topMotivoN} de {c.pierdeN})
|
||||||
|
{c.depu ? ` · ${c.depu} más son depuración sin motivo real` : ""}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>{c.depu} de {c.pierdeN} pérdidas son depuración sin motivo real — no hay una razón de negocio clara aquí</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
app/components/pipeline/DashBar.js
Normal file
27
app/components/pipeline/DashBar.js
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { agg } from "../../lib/derive";
|
||||||
|
|
||||||
|
// Barra horizontal con doble medida (# y $) — equivalente estático de dashBar() (pages/resumen.js),
|
||||||
|
// sin el cross-filter de clic (limitación conocida de esta v1).
|
||||||
|
export default function DashBar({ title, arr, dimKey }) {
|
||||||
|
const rows = agg(arr, dimKey, (o) => o.val ?? o.actual ?? 0).sort((a, b) => b.v - a.v);
|
||||||
|
const maxV = Math.max(...rows.map((d) => d.v), 1);
|
||||||
|
return (
|
||||||
|
<div className="panel dash-panel">
|
||||||
|
<h3>{title}</h3>
|
||||||
|
{rows.length ? (
|
||||||
|
rows.map((d) => (
|
||||||
|
<div className="dbar-row" key={d.k}>
|
||||||
|
<div className="dbar-top">
|
||||||
|
<span className="nm">{d.k}</span>
|
||||||
|
<span className="vals"><b>{d.n}</b><span className="c">{money(d.v)}</span></span>
|
||||||
|
</div>
|
||||||
|
<div className="bar-cell"><div className="bar-fill" style={{ width: `${((d.v / maxV) * 100).toFixed(1)}%` }} /></div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<p className="hint">Sin datos.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
43
app/components/pipeline/DashDonut.js
Normal file
43
app/components/pipeline/DashDonut.js
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { agg } from "../../lib/derive";
|
||||||
|
|
||||||
|
// Donut para Segmento — equivalente estático de dashDonut() (pages/resumen.js).
|
||||||
|
export default function DashDonut({ title, arr, dimKey }) {
|
||||||
|
const rows = agg(arr, dimKey, (o) => o.val ?? o.actual ?? 0).sort((a, b) => b.v - a.v);
|
||||||
|
const total = rows.reduce((s, d) => s + d.v, 0) || 1;
|
||||||
|
const R = 48, r = 30, C = 2 * Math.PI * R, cx = 64, cy = 64;
|
||||||
|
let acc = 0;
|
||||||
|
const color = (k) => (k === "Cartera Activa" ? "var(--alerta)" : "var(--marca)");
|
||||||
|
const arcs = rows.map((d) => {
|
||||||
|
const frac = d.v / total, len = frac * C, rot = (acc / C) * 360 - 90;
|
||||||
|
acc += len;
|
||||||
|
return (
|
||||||
|
<circle
|
||||||
|
key={d.k}
|
||||||
|
cx={cx} cy={cy} r={R} fill="none" stroke={color(d.k)} strokeWidth={r}
|
||||||
|
strokeDasharray={`${len.toFixed(2)} ${(C - len).toFixed(2)}`}
|
||||||
|
transform={`rotate(${rot.toFixed(2)} ${cx} ${cy})`}
|
||||||
|
>
|
||||||
|
<title>{d.k}: {d.n} oport. · {money(d.v)}</title>
|
||||||
|
</circle>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<div className="panel dash-panel">
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
|
||||||
|
<svg viewBox="0 0 128 128" width="128" height="128">{arcs}</svg>
|
||||||
|
<div style={{ flex: 1, minWidth: 150 }}>
|
||||||
|
{rows.length ? rows.map((d) => (
|
||||||
|
<div className="donut-leg-row" key={d.k}>
|
||||||
|
<span className="donut-dot" style={{ background: color(d.k) }} />
|
||||||
|
<span className="nm">{d.k}</span>
|
||||||
|
<span className="v">{d.n}</span>
|
||||||
|
<span className="c">{money(d.v)}</span>
|
||||||
|
</div>
|
||||||
|
)) : <p className="hint">Sin datos.</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
84
app/components/pipeline/ExecMatrix.js
Normal file
84
app/components/pipeline/ExecMatrix.js
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
import React from "react";
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { MTZ_DIMS, nomCorto } from "../../lib/derive";
|
||||||
|
import SegTabs from "../SegTabs";
|
||||||
|
|
||||||
|
// Matriz de ejecutivos × dimensión conmutable — puerto de mtzEjePanel() (assets/js/tables.js).
|
||||||
|
// `dims`/`activeDim` dejan elegir la columna (Plan/Categoría Previsión/Actividad/Temperatura/Fase)
|
||||||
|
// con pestañas — mismo patrón `SegTabs` + searchParam que el resto de la interactividad (Fase 1).
|
||||||
|
export default function ExecMatrix({ arr, titulo, hint, valor, dims = MTZ_DIMS, activeDim }) {
|
||||||
|
const val = valor || ((o) => o.est);
|
||||||
|
const d = dims.find((x) => x.k === activeDim) || dims[0];
|
||||||
|
const corto = d.corto;
|
||||||
|
let cols = [...new Set(arr.map((o) => o[d.k]).filter(Boolean))];
|
||||||
|
cols = d.orden ? cols.sort(d.orden) : cols;
|
||||||
|
const ejes = [...new Set(arr.map((o) => o.owner))].sort(
|
||||||
|
(a, b) => arr.filter((o) => o.owner === b).reduce((s, o) => s + val(o), 0) - arr.filter((o) => o.owner === a).reduce((s, o) => s + val(o), 0)
|
||||||
|
);
|
||||||
|
const cel = (ow, cv) => arr.filter((o) => o.owner === ow && o[d.k] === cv);
|
||||||
|
const maxN = Math.max(...ejes.flatMap((ow) => cols.map((c) => cel(ow, c).length)), 1);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="panel">
|
||||||
|
<h3>{titulo || "Tubería por ejecutivo"}</h3>
|
||||||
|
<p className="hint">{hint || "La intensidad del azul es la cantidad de oportunidades"}</p>
|
||||||
|
<div style={{ marginBottom: 12 }}>
|
||||||
|
<SegTabs tabs={dims.map((x) => ({ k: x.k, lbl: x.lbl }))} activeKey={d.k} paramName="mze" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mze"
|
||||||
|
style={{ gridTemplateColumns: `minmax(120px,1.4fr) repeat(${cols.length},minmax(58px,1fr)) minmax(74px,.9fr)` }}
|
||||||
|
>
|
||||||
|
<div className="mze-h eje" />
|
||||||
|
{cols.map((c) => <div className="mze-h" key={c} title={c}>{corto(c)}</div>)}
|
||||||
|
<div className="mze-h tot">Total</div>
|
||||||
|
{ejes.map((ow) => {
|
||||||
|
const tot = arr.filter((o) => o.owner === ow);
|
||||||
|
return (
|
||||||
|
<React.Fragment key={ow}>
|
||||||
|
<div className="mze-r">{nomCorto(ow)}</div>
|
||||||
|
{cols.map((c) => {
|
||||||
|
const e = cel(ow, c);
|
||||||
|
const alpha = e.length ? (0.1 + 0.55 * (e.length / maxN)).toFixed(2) : 0;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`mze-c${e.length ? "" : " vacia"}`}
|
||||||
|
key={`${ow}-${c}`}
|
||||||
|
style={e.length ? { background: `rgba(30,113,184,${alpha})` } : undefined}
|
||||||
|
>
|
||||||
|
{e.length ? (
|
||||||
|
<>
|
||||||
|
<span className="n">{e.length}</span>
|
||||||
|
<span className="v">{money(e.reduce((s, o) => s + val(o), 0))}</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span className="n vacio">·</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-c tot">
|
||||||
|
<span className="n">{tot.length}</span>
|
||||||
|
<span className="v">{money(tot.reduce((s, o) => s + val(o), 0))}</span>
|
||||||
|
</div>
|
||||||
|
</React.Fragment>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-r tot">Total</div>
|
||||||
|
{cols.map((c) => {
|
||||||
|
const e = arr.filter((o) => o[d.k] === c);
|
||||||
|
return (
|
||||||
|
<div className="mze-c tot" key={`pie-${c}`}>
|
||||||
|
<span className="n">{e.length}</span>
|
||||||
|
<span className="v">{money(e.reduce((s, o) => s + val(o), 0))}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<div className="mze-c tot">
|
||||||
|
<span className="n">{arr.length}</span>
|
||||||
|
<span className="v">{money(arr.reduce((s, o) => s + val(o), 0))}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
60
app/components/pipeline/MatrizCalidad.js
Normal file
60
app/components/pipeline/MatrizCalidad.js
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
import React from "react";
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { CALIDAD_ORDER, CALIDAD_COLOR } from "../../lib/derive";
|
||||||
|
import FilterableRow from "../FilterableRow";
|
||||||
|
|
||||||
|
// Matriz calidad × movimiento — el cruce que convierte "N estancadas" (inaccionable) en
|
||||||
|
// "N oportunidades que el CRM califica como buenas y nadie mueve" (ver tables.js del sitio HTML).
|
||||||
|
export default function MatrizCalidad({ arr }) {
|
||||||
|
const cols = ["En movimiento", "Estancada"];
|
||||||
|
const cel = (cal, mv) => arr.filter((o) => o.calidad === cal && o.mov === mv);
|
||||||
|
const totCol = (mv) => arr.filter((o) => o.mov === mv);
|
||||||
|
const filas = CALIDAD_ORDER.filter((cal) => arr.some((o) => o.calidad === cal));
|
||||||
|
const foco = cel("Alta", "Estancada");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="panel" id="mtzPanel">
|
||||||
|
<h3>Calidad × movimiento</h3>
|
||||||
|
<p className="hint">Termómetro (Alta = Caliente/Hirviendo) contra estancamiento</p>
|
||||||
|
<div className="mtz">
|
||||||
|
<div className="mtz-h" />
|
||||||
|
{cols.map((c) => (
|
||||||
|
<div className={`mtz-h${c === "Estancada" ? " alerta" : ""}`} key={c}>{c}</div>
|
||||||
|
))}
|
||||||
|
{filas.map((cal) => (
|
||||||
|
<React.Fragment key={cal}>
|
||||||
|
<div className="mtz-r">
|
||||||
|
<span style={{ color: CALIDAD_COLOR[cal], fontWeight: 700 }}>●</span> {cal}
|
||||||
|
</div>
|
||||||
|
{cols.map((mv) => {
|
||||||
|
const e = cel(cal, mv);
|
||||||
|
const isFoco = cal === "Alta" && mv === "Estancada";
|
||||||
|
return (
|
||||||
|
<FilterableRow
|
||||||
|
as="div"
|
||||||
|
key={`${cal}-${mv}`}
|
||||||
|
pairs={[["calidad", cal], ["mov", mv]]}
|
||||||
|
className={`mtz-c${isFoco ? " foco" : ""}`}
|
||||||
|
>
|
||||||
|
<span className="n">{e.length}</span>
|
||||||
|
<span className="v">{money(e.reduce((s, o) => s + o.est, 0))}</span>
|
||||||
|
</FilterableRow>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
|
<div className="mtz-r tot">Total</div>
|
||||||
|
{cols.map((mv) => (
|
||||||
|
<div className="mtz-c tot" key={`tot-${mv}`}>
|
||||||
|
<span className="n">{totCol(mv).length}</span>
|
||||||
|
<span className="v">{money(totCol(mv).reduce((s, o) => s + o.est, 0))}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<p className="hint" style={{ marginTop: 10 }}>
|
||||||
|
■ <b>{foco.length}</b> de calidad alta sin movimiento — <b>{money(foco.reduce((s, o) => s + o.est, 0))}</b>.
|
||||||
|
Es la celda que hay que vaciar.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
58
app/components/pipeline/Panel.js
Normal file
58
app/components/pipeline/Panel.js
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import FilterableRow from "../FilterableRow";
|
||||||
|
|
||||||
|
// Panel de barras — puerto de `panel()` del sitio HTML (ver assets/js/tables.js). Si se pasa
|
||||||
|
// `dimKey`, cada fila es clicleable y filtra la página entera por `o[dimKey] === d.k` (ver
|
||||||
|
// lib/filterState.js); sin `dimKey` queda estático (paneles donde filtrar no aplica).
|
||||||
|
export default function Panel({ title, hint, rows, cls, top, byVal, hideMoney, dimKey }) {
|
||||||
|
let arr = rows;
|
||||||
|
if (byVal) arr = [...arr].sort((a, b) => b.v - a.v);
|
||||||
|
const maxN = byVal ? Math.max(...arr.map((d) => d.v), 1) : Math.max(...arr.map((d) => d.n), 1);
|
||||||
|
let vis = arr, resto = null;
|
||||||
|
if (top && arr.length > top + 1) {
|
||||||
|
vis = arr.slice(0, top);
|
||||||
|
const r = arr.slice(top);
|
||||||
|
resto = { n: r.reduce((a, d) => a + d.n, 0), v: r.reduce((a, d) => a + d.v, 0), k: r.length };
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="panel">
|
||||||
|
<h3>{title}</h3>
|
||||||
|
{hint && <p className="hint">{hint}</p>}
|
||||||
|
{vis.map((d) => {
|
||||||
|
const inner = (
|
||||||
|
<>
|
||||||
|
<div className="bl">
|
||||||
|
<span className="nm" title={d.k}>{d.k}</span>
|
||||||
|
</div>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div className={`bar-fill ${cls || ""}`} style={{ width: `${(((byVal ? d.v : d.n) / maxN) * 100).toFixed(1)}%` }} />
|
||||||
|
</div>
|
||||||
|
<span className="v">{d.n}</span>
|
||||||
|
{!hideMoney && <span className="c">{money(d.v)}</span>}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
return dimKey ? (
|
||||||
|
<FilterableRow key={d.k} pairs={[[dimKey, d.k]]} className="row dual">
|
||||||
|
{inner}
|
||||||
|
</FilterableRow>
|
||||||
|
) : (
|
||||||
|
<div className="row dual static" key={d.k}>{inner}</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{resto && (
|
||||||
|
<div className="row dual static">
|
||||||
|
<div className="bl">
|
||||||
|
<span className="nm" style={{ color: "var(--tinta-suave)", fontStyle: "italic" }}>
|
||||||
|
Otros ({resto.k} categorías)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div className={`bar-fill ${cls || ""}`} style={{ width: `${(((byVal ? resto.v : resto.n) / maxN) * 100).toFixed(1)}%`, opacity: 0.45 }} />
|
||||||
|
</div>
|
||||||
|
<span className="v">{resto.n}</span>
|
||||||
|
{!hideMoney && <span className="c">{money(resto.v)}</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
106
app/components/pipeline/TablaPipe.js
Normal file
106
app/components/pipeline/TablaPipe.js
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
import { DYN, ACT_COLOR, money, money2 } from "../../lib/constants";
|
||||||
|
|
||||||
|
const PLAN_LETRA = {
|
||||||
|
"Plan A - En firma": "A", "Plan B - En Negociación": "B", "Plan C - En seguimiento": "C",
|
||||||
|
"Plan D - Recalificar": "D", "Sin plan de cierre": "—",
|
||||||
|
};
|
||||||
|
const nomCorto = (n) => {
|
||||||
|
const p = (n || "").split(" ");
|
||||||
|
return p.length > 2 ? `${p[0]} ${p[p.length - 2]}` : n || "";
|
||||||
|
};
|
||||||
|
function cierreVencido(o) {
|
||||||
|
return !!o.close && o.close < new Date().toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tabla de tubería para el layout split23 (2/3 der.): columna Cliente/Oportunidad fija, scroll
|
||||||
|
// horizontal — mismo tratamiento que `tablePipe(arr,tipo,split=true,...)` del sitio HTML
|
||||||
|
// (assets/js/tables.js). Sin agrupado por actividad agendada todavía (necesita datos de
|
||||||
|
// Actividades, que esta app aún no consulta) y sin clic-para-agendar.
|
||||||
|
export default function TablaPipe({ arr, tipo }) {
|
||||||
|
const colFc = tipo === "fc";
|
||||||
|
const sorted = [...arr].sort((a, b) => b.est - a.est);
|
||||||
|
return (
|
||||||
|
<div className="tw split">
|
||||||
|
<div className="ts">
|
||||||
|
<table className="fix">
|
||||||
|
<colgroup>
|
||||||
|
<col style={{ width: "20%" }} />
|
||||||
|
<col style={{ width: "64px" }} />
|
||||||
|
<col style={{ width: "32px" }} />
|
||||||
|
<col style={{ width: "8.5%" }} />
|
||||||
|
<col style={{ width: "8.5%" }} />
|
||||||
|
<col style={{ width: "8.5%" }} />
|
||||||
|
<col style={{ width: "36px" }} />
|
||||||
|
<col style={{ width: "70px" }} />
|
||||||
|
<col style={{ width: "9%" }} />
|
||||||
|
<col style={{ width: "8.5%" }} />
|
||||||
|
{colFc && <col style={{ width: "7.5%" }} />}
|
||||||
|
<col style={{ width: "7%" }} />
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente / Oportunidad</th>
|
||||||
|
<th>Segmento</th>
|
||||||
|
<th title="Plan de cierre">Plan</th>
|
||||||
|
<th>Línea</th>
|
||||||
|
<th>Competidor</th>
|
||||||
|
<th>Fase</th>
|
||||||
|
<th className="num" title="Días en la fase actual">Días</th>
|
||||||
|
<th>Actividad</th>
|
||||||
|
<th>Ejecutivo</th>
|
||||||
|
<th className="num">MRR est.</th>
|
||||||
|
{colFc && <th className="num">Forecast</th>}
|
||||||
|
<th>Cierre</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sorted.map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td className="dual-cel">
|
||||||
|
{o.actFecha && (
|
||||||
|
<span title={`Actividad agendada para el ${o.actFecha}`}>📅 </span>
|
||||||
|
)}
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener" title={o.name}>
|
||||||
|
{o.name}
|
||||||
|
</a>
|
||||||
|
<span className="sub" title={o.cliente || ""}>{o.cliente || "—"}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`} title={o.segmento}>
|
||||||
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`plan-b p${PLAN_LETRA[o.plan] || "x"}`} title={o.plan || "Sin plan de cierre"}>
|
||||||
|
{PLAN_LETRA[o.plan] || "—"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="elip" title={o.linea || ""}>{o.linea || "—"}</td>
|
||||||
|
<td className="elip" title={o.competidor || ""}>
|
||||||
|
{o.competidor === "Sin registrar" ? "—" : o.competidor || "—"}
|
||||||
|
</td>
|
||||||
|
<td className="elip" title={o.faseActual || ""}>{o.faseActual || "—"}</td>
|
||||||
|
<td className="num">{o.diasEnFase == null ? "—" : o.diasEnFase}</td>
|
||||||
|
<td style={{ textAlign: "center" }}>
|
||||||
|
<span
|
||||||
|
style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }}
|
||||||
|
title={`${o.actividad}${o.estanc ? " · estancada" : ""}`}
|
||||||
|
>
|
||||||
|
●
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="elip" title={o.owner}>{nomCorto(o.owner)}</td>
|
||||||
|
<td className="num">{money(o.est)}</td>
|
||||||
|
{colFc && <td className="num">{money(o.fc)}</td>}
|
||||||
|
<td className={`num${cierreVencido(o) ? " venc" : ""}`} title={cierreVencido(o) ? "Fecha de cierre vencida al corte" : ""}>
|
||||||
|
{o.close ? o.close.slice(5) : "—"}
|
||||||
|
{cierreVencido(o) ? " ⚠" : ""}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
55
app/components/pipeline/WonTable.js
Normal file
55
app/components/pipeline/WonTable.js
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
import { DYN, money2 } from "../../lib/constants";
|
||||||
|
|
||||||
|
// Tabla de detalle de ganadas — equivalente de tableWon() (assets/js/tables.js), sin el orden
|
||||||
|
// clicleable por encabezado (limitación conocida de esta v1).
|
||||||
|
export default function WonTable({ rows, title, locked }) {
|
||||||
|
const sorted = [...rows].sort((a, b) => (b.val ?? b.actual ?? 0) - (a.val ?? a.actual ?? 0));
|
||||||
|
return (
|
||||||
|
<div className="tw">
|
||||||
|
{title && (
|
||||||
|
<div className="tw-title">
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<span className="tw-count">{sorted.length} oportunidades</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Seg.</th>
|
||||||
|
{!locked && <th>Ejecutivo</th>}
|
||||||
|
<th>Tipo</th>
|
||||||
|
<th>Línea de Negocio</th>
|
||||||
|
<th>Origen</th>
|
||||||
|
<th className="num">MRR</th>
|
||||||
|
<th>Cierre</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sorted.map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td className="wrap-p">{o.cliente || "—"}</td>
|
||||||
|
<td className="wrap-p">
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||||
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
{!locked && <td>{o.owner}</td>}
|
||||||
|
<td>{o.tipo}</td>
|
||||||
|
<td>{o.linea}</td>
|
||||||
|
<td className="wrap-p">{o.origen}</td>
|
||||||
|
<td className="num">{money2(o.val ?? o.actual)}</td>
|
||||||
|
<td>{o.actualClose || o.cierre || "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/detalle/loading.js
Normal file
4
app/detalle/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
149
app/detalle/page.js
Normal file
149
app/detalle/page.js
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
import Link from "next/link";
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getPipeline, getClosed } from "../lib/queries";
|
||||||
|
import { PLAN_ORDER } from "../lib/derive";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import PlanFilterSelect from "../components/PlanFilterSelect";
|
||||||
|
import { DYN, ACT_COLOR, money2 } from "../lib/constants";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SETS = [
|
||||||
|
{ key: "pipe", label: "Tubería activa" },
|
||||||
|
{ key: "ganadas", label: "Ganadas" },
|
||||||
|
{ key: "perdidas", label: "Perdidas" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function DetallePage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner, set, plan } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const detSet = SETS.some((s) => s.key === set) ? set : "pipe";
|
||||||
|
const mes = currentMonth();
|
||||||
|
|
||||||
|
let rows;
|
||||||
|
try {
|
||||||
|
if (detSet === "pipe") rows = await getPipeline(session.accessToken, scope);
|
||||||
|
else if (detSet === "ganadas") rows = await getClosed(session.accessToken, scope, 1, mes);
|
||||||
|
else rows = await getClosed(session.accessToken, scope, 2, mes);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const planesDisponibles = detSet === "pipe" ? PLAN_ORDER.filter((p) => rows.some((o) => (o.plan || "Sin plan de cierre") === p)) : [];
|
||||||
|
const filtrados = detSet === "pipe" && plan ? rows.filter((o) => (o.plan || "Sin plan de cierre") === plan) : rows;
|
||||||
|
const sorted = [...filtrados].sort((a, b) => (b.est ?? b.actual ?? 0) - (a.est ?? a.actual ?? 0));
|
||||||
|
|
||||||
|
const qs = (key) => {
|
||||||
|
const p = new URLSearchParams();
|
||||||
|
if (owner) p.set("owner", owner);
|
||||||
|
p.set("set", key);
|
||||||
|
return `/detalle?${p.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>Detalle</h2>
|
||||||
|
|
||||||
|
<div className="seg-tabs" style={{ marginBottom: 16 }}>
|
||||||
|
{SETS.map((s) => (
|
||||||
|
<Link key={s.key} href={qs(s.key)} className={detSet === s.key ? "on" : ""}>
|
||||||
|
<button className={detSet === s.key ? "on" : ""} type="button">
|
||||||
|
{s.label}
|
||||||
|
</button>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{detSet === "pipe" && planesDisponibles.length > 0 && (
|
||||||
|
<div style={{ marginBottom: 12 }}>
|
||||||
|
<PlanFilterSelect options={planesDisponibles} current={plan} baseHref={qs("pipe")} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="hint" style={{ marginBottom: 12 }}>
|
||||||
|
{sorted.length} oportunidades{detSet !== "pipe" ? ` (${mes})` : ""} · clic en el nombre abre la oportunidad en
|
||||||
|
Dynamics 365.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{sorted.length === 0 ? (
|
||||||
|
<p>No hay oportunidades para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Seg.</th>
|
||||||
|
{!scope.locked && <th>Ejecutivo</th>}
|
||||||
|
{detSet === "pipe" ? (
|
||||||
|
<>
|
||||||
|
<th>Plan cierre</th>
|
||||||
|
<th>Fase actual</th>
|
||||||
|
<th>Actividad</th>
|
||||||
|
<th className="num">MRR est.</th>
|
||||||
|
<th className="num">Forecast</th>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<th>Tipo</th>
|
||||||
|
<th className="num">MRR</th>
|
||||||
|
<th>Cierre</th>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sorted.map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td>{o.cliente || "—"}</td>
|
||||||
|
<td>
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||||
|
{o.name}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||||
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
{!scope.locked && <td>{o.owner}</td>}
|
||||||
|
{detSet === "pipe" ? (
|
||||||
|
<>
|
||||||
|
<td>{(o.plan || "").replace(" - ", " ")}</td>
|
||||||
|
<td>{o.faseActual || "—"}</td>
|
||||||
|
<td>
|
||||||
|
<span style={{ color: ACT_COLOR[o.actividad] || "#9db4c9", fontWeight: 700 }}>
|
||||||
|
● {o.actividad}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="num">{money2(o.est)}</td>
|
||||||
|
<td className="num">{money2(o.fc)}</td>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<td>{o.tipo}</td>
|
||||||
|
<td className="num">{money2(o.actual)}</td>
|
||||||
|
<td>{o.actualClose || "—"}</td>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
34
app/diagnostico/page.js
Normal file
34
app/diagnostico/page.js
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { dv } from "../lib/dataverse";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
async function checkDataverse(accessToken) {
|
||||||
|
try {
|
||||||
|
const data = await dv("systemusers?$select=fullname&$top=1", accessToken);
|
||||||
|
return { ok: true, sample: data.value?.[0]?.fullname };
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: e.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function DiagnosticoPage() {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const check = session.accessToken ? await checkDataverse(session.accessToken) : { ok: false, error: "sin accessToken" };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>Diagnóstico</h2>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Correo:</strong> {session.email}</li>
|
||||||
|
<li><strong>Rol:</strong> {session.isAdmin ? "Administrador" : "Vendedor"}</li>
|
||||||
|
<li><strong>Token de Dataverse:</strong> {check.ok ? "✅ funciona" : `❌ ${check.error}`}</li>
|
||||||
|
{check.ok && <li><strong>Prueba de lectura:</strong> {check.sample}</li>}
|
||||||
|
{session.error && <li style={{ color: "red" }}><strong>Error de sesión:</strong> {session.error}</li>}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/ganadas/loading.js
Normal file
4
app/ganadas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
184
app/ganadas/page.js
Normal file
184
app/ganadas/page.js
Normal file
|
|
@ -0,0 +1,184 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getClosed, getSystemUsers } from "../lib/queries";
|
||||||
|
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||||
|
import { getMetas, getMetaGlobal } from "../lib/metas";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import Panel from "../components/pipeline/Panel";
|
||||||
|
import FilterChips from "../components/FilterChips";
|
||||||
|
import { DYN, money, money2 } from "../lib/constants";
|
||||||
|
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const DIM_LABELS = { tipo: "Tipo", linea: "Línea", origen: "Origen", campaign: "Campaña" };
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function GanadasPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const mes = currentMonth();
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
|
||||||
|
let wonAll, lostAll, allUsers;
|
||||||
|
try {
|
||||||
|
[wonAll, lostAll, allUsers] = await Promise.all([
|
||||||
|
getClosed(session.accessToken, scope, 1, mes),
|
||||||
|
getClosed(session.accessToken, scope, 2, mes),
|
||||||
|
getSystemUsers(session.accessToken),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
const won = applyFilt(wonAll, filt);
|
||||||
|
const lost = applyFilt(lostAll, filt);
|
||||||
|
|
||||||
|
const metas = getMetas();
|
||||||
|
const metaGlobal = getMetaGlobal();
|
||||||
|
|
||||||
|
const sumW = won.reduce((a, o) => a + (o.actual || 0), 0);
|
||||||
|
const arpu = won.length ? sumW / won.length : 0;
|
||||||
|
const conv = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
|
||||||
|
const cumplGlobal = metaGlobal ? Math.round((sumW / metaGlobal) * 100) : null;
|
||||||
|
|
||||||
|
const porEjecutivo = EJECUTIVOS_VENTA.map((nombre) => {
|
||||||
|
const w = won.filter((o) => o.owner === nombre);
|
||||||
|
const logrado = w.reduce((a, o) => a + (o.actual || 0), 0);
|
||||||
|
const email = allUsers.find((u) => u.name === nombre)?.email;
|
||||||
|
const meta = email ? metas[email] : null;
|
||||||
|
const pct = meta ? Math.round((logrado / meta) * 100) : null;
|
||||||
|
return { nombre, logrado, meta, pct };
|
||||||
|
}).sort((a, b) => (b.pct ?? -1) - (a.pct ?? -1));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Ventas Ganadas — {mes}</h2>
|
||||||
|
<OwnerControl
|
||||||
|
owners={owners}
|
||||||
|
current={scope.locked ? session.email : scope.email}
|
||||||
|
locked={scope.locked}
|
||||||
|
lockedLabel={session.email}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money2(sumW)}</span>
|
||||||
|
<span className="l">Suma ingresos reales</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{won.length}</span>
|
||||||
|
<span className="l">Oportunidades ganadas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money2(arpu)}</span>
|
||||||
|
<span className="l">ARPU logrado</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{conv}%</span>
|
||||||
|
<span className="l">% Conversión</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={cumplGlobal != null && cumplGlobal < 70 ? "n pierde" : "n"}>
|
||||||
|
{cumplGlobal != null ? `${cumplGlobal}%` : "n/d"}
|
||||||
|
</span>
|
||||||
|
<span className="l">Cumplimiento equipo</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Cumplimiento de meta por ejecutivo</h3>
|
||||||
|
<p className="hint">Ingresos reales ÷ meta mensual · verde ≥70% · ámbar 50-69% · rojo <50%</p>
|
||||||
|
{porEjecutivo.map((r) => (
|
||||||
|
<div className="row static" key={r.nombre}>
|
||||||
|
<div className="bl">
|
||||||
|
<span className="nm">{r.nombre}</span>
|
||||||
|
</div>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div
|
||||||
|
className={`bar-fill ${r.pct == null ? "" : r.pct >= 70 ? "" : r.pct >= 50 ? "alerta" : "pierde"}`}
|
||||||
|
style={{ width: `${Math.min(100, r.pct ?? 0)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="v">{r.pct == null ? "n/d" : `${r.pct}%`}</span>
|
||||||
|
<span className="c">
|
||||||
|
{money(r.logrado)}
|
||||||
|
{r.meta ? `/${money(r.meta)}` : ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
<div className="grid2">
|
||||||
|
<Panel title="Por Tipo de Oportunidad" rows={agg(won, "tipo", (o) => o.actual)} dimKey="tipo" />
|
||||||
|
<Panel title="Por Línea de Negocio" rows={agg(won, "linea", (o) => o.actual)} dimKey="linea" />
|
||||||
|
<Panel title="Por Origen" rows={agg(won, "origen", (o) => o.actual)} dimKey="origen" />
|
||||||
|
<Panel title="Por Campaña de Origen" rows={agg(won, "campaign", (o) => o.actual)} top={7} dimKey="campaign" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de oportunidades ganadas</h3>
|
||||||
|
<p className="hint">Clic en el nombre abre la oportunidad en Dynamics 365</p>
|
||||||
|
</div>
|
||||||
|
{won.length === 0 ? (
|
||||||
|
<p>No hay oportunidades ganadas en este período para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Seg.</th>
|
||||||
|
{!scope.locked && <th>Ejecutivo</th>}
|
||||||
|
<th>Tipo</th>
|
||||||
|
<th>Línea de Negocio</th>
|
||||||
|
<th>Origen</th>
|
||||||
|
<th className="num">MRR</th>
|
||||||
|
<th>Cierre</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{[...won].sort((a, b) => b.actual - a.actual).map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td>{o.cliente || "—"}</td>
|
||||||
|
<td>
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||||
|
{o.name}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||||
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
{!scope.locked && <td>{o.owner}</td>}
|
||||||
|
<td>{o.tipo}</td>
|
||||||
|
<td>{o.linea}</td>
|
||||||
|
<td>{o.origen}</td>
|
||||||
|
<td className="num">{money2(o.actual)}</td>
|
||||||
|
<td>{o.actualClose || "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
app/globals.css
Normal file
10
app/globals.css
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
.login-btn {
|
||||||
|
font-family: var(--sans);
|
||||||
|
font-size: 13px;
|
||||||
|
padding: 7px 14px;
|
||||||
|
border: 1px solid var(--marca);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--marca);
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
66
app/layout.js
Normal file
66
app/layout.js
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import "./globals.css";
|
||||||
|
import { auth, signIn, signOut } from "./lib/auth";
|
||||||
|
import AppShell from "./components/AppShell";
|
||||||
|
|
||||||
|
export const metadata = {
|
||||||
|
title: "Informe Comercial ALFA+",
|
||||||
|
description: "Analítica comercial en vivo sobre Dynamics 365",
|
||||||
|
};
|
||||||
|
|
||||||
|
// Mismo orden y agrupación que assets/js/utils.js del sitio HTML — no reordenar sin actualizar
|
||||||
|
// también ese archivo, se desincronizan los dos diseños.
|
||||||
|
const PAGES = [
|
||||||
|
{ href: "/", label: "Agenda", ico: "🗓", grupo: "Actividades", built: true },
|
||||||
|
{ href: "/actividades", label: "Plan de Actividades", ico: "✓", grupo: "Actividades", built: true },
|
||||||
|
|
||||||
|
{ href: "/prevision", label: "Previsión de Ventas", ico: "◎", grupo: "Ventas", built: true },
|
||||||
|
{ href: "/tuberia", label: "Tubería de Ventas", ico: "▤", grupo: "Ventas", built: true },
|
||||||
|
{ href: "/resumen", label: "Ventas Resumen", ico: "▣", grupo: "Ventas", built: true },
|
||||||
|
{ href: "/ganadas", label: "Oportunidades Ganadas", ico: "▲", grupo: "Ventas", built: true },
|
||||||
|
{ href: "/perdemos", label: "Oportunidades Perdidas", ico: "▼", grupo: "Ventas", built: true },
|
||||||
|
{ href: "/tendencia", label: "Tendencia", ico: "📈", grupo: "Ventas", built: true },
|
||||||
|
|
||||||
|
{ href: "/renovaciones/prevision", label: "Previsión de Renovaciones", ico: "◍", grupo: "Renovaciones", built: true },
|
||||||
|
{ href: "/renovaciones/tuberia", label: "Tubería de Renovaciones", ico: "▥", grupo: "Renovaciones", built: true },
|
||||||
|
{ href: "/renovaciones/logradas", label: "Renovaciones Logradas", ico: "♻", grupo: "Renovaciones", built: true },
|
||||||
|
{ href: "/renovaciones/perdidas", label: "Renovaciones Perdidas", ico: "✖", grupo: "Renovaciones", built: true },
|
||||||
|
|
||||||
|
{ href: "/nuevas", label: "Nuevas Oportunidades", ico: "◔", grupo: "Análisis", built: true },
|
||||||
|
{ href: "/mapa", label: "Mapa Geográfico", ico: "◈", grupo: "Análisis", built: false },
|
||||||
|
{ href: "/precio", label: "Precio por Mbps", ico: "⊟", grupo: "Análisis", built: false },
|
||||||
|
{ href: "/detalle", label: "Detalle", ico: "☰", grupo: "Análisis", built: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default async function RootLayout({ children }) {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
async function handleSignIn() {
|
||||||
|
"use server";
|
||||||
|
await signIn("microsoft-entra-id");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSignOut() {
|
||||||
|
"use server";
|
||||||
|
await signOut();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<html lang="es">
|
||||||
|
<head>
|
||||||
|
<link rel="stylesheet" href="/assets/css/base.css" />
|
||||||
|
<link rel="stylesheet" href="/assets/css/layout.css" />
|
||||||
|
<link rel="stylesheet" href="/assets/css/components.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<AppShell
|
||||||
|
pages={PAGES}
|
||||||
|
session={session?.email ? { email: session.email, isAdmin: session.isAdmin } : null}
|
||||||
|
onSignIn={handleSignIn}
|
||||||
|
onSignOut={handleSignOut}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AppShell>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
72
app/lib/auth.js
Normal file
72
app/lib/auth.js
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
import NextAuth from "next-auth";
|
||||||
|
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";
|
||||||
|
|
||||||
|
const DV = process.env.DATAVERSE_URL; // https://<org>.crm.dynamics.com
|
||||||
|
|
||||||
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||||
|
trustHost: true,
|
||||||
|
providers: [
|
||||||
|
MicrosoftEntraID({
|
||||||
|
clientId: process.env.AZURE_CLIENT_ID,
|
||||||
|
clientSecret: process.env.AZURE_CLIENT_SECRET,
|
||||||
|
issuer: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/v2.0`,
|
||||||
|
authorization: {
|
||||||
|
params: {
|
||||||
|
scope: `openid profile email offline_access ${DV}/user_impersonation`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
callbacks: {
|
||||||
|
async jwt({ token, account }) {
|
||||||
|
if (account) {
|
||||||
|
token.accessToken = account.access_token;
|
||||||
|
token.refreshToken = account.refresh_token;
|
||||||
|
token.expiresAt = account.expires_at;
|
||||||
|
}
|
||||||
|
if (token.expiresAt && Date.now() / 1000 > token.expiresAt - 300 && token.refreshToken) {
|
||||||
|
try {
|
||||||
|
const r = await fetch(
|
||||||
|
`https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}/oauth2/v2.0/token`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: new URLSearchParams({
|
||||||
|
client_id: process.env.AZURE_CLIENT_ID,
|
||||||
|
client_secret: process.env.AZURE_CLIENT_SECRET,
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: token.refreshToken,
|
||||||
|
scope: `openid profile email offline_access ${DV}/user_impersonation`,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (r.ok) {
|
||||||
|
const d = await r.json();
|
||||||
|
token.accessToken = d.access_token;
|
||||||
|
token.expiresAt = Math.floor(Date.now() / 1000) + d.expires_in;
|
||||||
|
if (d.refresh_token) token.refreshToken = d.refresh_token;
|
||||||
|
} else {
|
||||||
|
token.error = "RefreshFailed";
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
token.error = "RefreshFailed";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
async session({ session, token }) {
|
||||||
|
session.accessToken = token.accessToken;
|
||||||
|
session.error = token.error;
|
||||||
|
const email = (session.user?.email || "").toLowerCase();
|
||||||
|
session.email = email;
|
||||||
|
session.isAdmin = (process.env.ADMIN_EMAILS || "")
|
||||||
|
.toLowerCase()
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.includes(email);
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
session: { strategy: "jwt" },
|
||||||
|
});
|
||||||
9
app/lib/authz.js
Normal file
9
app/lib/authz.js
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
export function ownerFilter(session, requestedOwnerEmail) {
|
||||||
|
if (!session?.email) throw new Error("NO_SESSION");
|
||||||
|
|
||||||
|
// Vendedor: siempre su propio correo, ignorando lo que pida el cliente.
|
||||||
|
if (!session.isAdmin) return { email: session.email, locked: true };
|
||||||
|
|
||||||
|
// Admin: puede pedir un vendedor concreto, o todos.
|
||||||
|
return { email: requestedOwnerEmail || null, locked: false };
|
||||||
|
}
|
||||||
19
app/lib/constants.js
Normal file
19
app/lib/constants.js
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
export const DYN =
|
||||||
|
"https://alfanumeric.crm.dynamics.com/main.aspx?appid=eb8b70d7-5a69-e911-a998-000d3a1a42fe&pagetype=entityrecord&etn=opportunity&id=";
|
||||||
|
|
||||||
|
const ACT_ETN = { Tarea: "task", Cita: "appointment", Llamada: "phonecall" };
|
||||||
|
export function actividadUrl(a) {
|
||||||
|
return DYN.replace("etn=opportunity", `etn=${ACT_ETN[a.tipo] || "phonecall"}`) + a.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ACT_COLOR = {
|
||||||
|
Activa: "#3f7d5c",
|
||||||
|
Tibia: "#C98A1B",
|
||||||
|
Fría: "#d1642a",
|
||||||
|
Congelada: "#B23A2E",
|
||||||
|
"Sin dato": "#9db4c9",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const money = (n) => "$" + Math.round(n || 0).toLocaleString("en-US");
|
||||||
|
export const money2 = (n) =>
|
||||||
|
"$" + (n || 0).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
54
app/lib/dataverse.js
Normal file
54
app/lib/dataverse.js
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
const BASE = `${process.env.DATAVERSE_URL}/api/data/v9.2`;
|
||||||
|
const MAX_RETRIES = 3;
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reintenta 429 (throttling de Dataverse) respetando Retry-After — ver migration.md §8.
|
||||||
|
export async function dv(path, accessToken, attempt = 0) {
|
||||||
|
const r = await fetch(`${BASE}/${path}`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
Accept: "application/json",
|
||||||
|
"OData-MaxVersion": "4.0",
|
||||||
|
"OData-Version": "4.0",
|
||||||
|
// FormattedValue: etiqueta legible de option sets. lookuplogicalname: qué entidad es un lookup
|
||||||
|
// polimórfico (ej. "Referente a" de una actividad puede ser cuenta U oportunidad) — sin esto
|
||||||
|
// no hay forma de saber a qué tabla apunta un _regardingobjectid_value.
|
||||||
|
Prefer: 'odata.include-annotations="OData.Community.Display.V1.FormattedValue,Microsoft.Dynamics.CRM.lookuplogicalname"',
|
||||||
|
},
|
||||||
|
// Caché de 4 min en vez de no-store — decisión revisada: la versión 100% en vivo (sin caché)
|
||||||
|
// tardaba 2-4s por página. Subido de 90s a 240s (2026-09-22, a pedido de Marco tras seguir
|
||||||
|
// viendo 4s): más frecuencia de reuso de caché, a cambio de hasta 4 min de atraso en vez de
|
||||||
|
// 1.5 — razonable para un informe que se consulta, no un panel en tiempo real. El alcance
|
||||||
|
// (owner) ya viaja en la URL vía $filter, así que cachear por URL no filtra datos entre
|
||||||
|
// usuarios con distinto alcance — la Capa 2 de autorización (ownerFilter) sigue siendo la que
|
||||||
|
// decide qué URL se pide, no el token. Ver migration.md §8, "plan B" ya documentado ahí.
|
||||||
|
next: { revalidate: 240 },
|
||||||
|
});
|
||||||
|
if (r.status === 401) throw new Error("TOKEN_EXPIRED");
|
||||||
|
if (r.status === 429 && attempt < MAX_RETRIES) {
|
||||||
|
const retryAfter = Number(r.headers.get("Retry-After")) || 2 ** attempt;
|
||||||
|
await sleep(retryAfter * 1000);
|
||||||
|
return dv(path, accessToken, attempt + 1);
|
||||||
|
}
|
||||||
|
if (!r.ok) throw new Error(`DATAVERSE_${r.status}: ${(await r.text()).slice(0, 300)}`);
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Etiqueta legible de un option set, entregada por el header Prefer de arriba.
|
||||||
|
export function fv(o, key) {
|
||||||
|
return o[`${key}@OData.Community.Display.V1.FormattedValue`] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A qué entidad apunta un lookup polimórfico — key con el mismo formato que fv(), ej.
|
||||||
|
// lookupType(o, "_regardingobjectid_value").
|
||||||
|
export function lookupType(o, key) {
|
||||||
|
return o[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function odataString(s) {
|
||||||
|
return String(s).replace(/'/g, "''");
|
||||||
|
}
|
||||||
|
|
||||||
35
app/lib/db.js
Normal file
35
app/lib/db.js
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import Database from "better-sqlite3";
|
||||||
|
import path from "node:path";
|
||||||
|
import fs from "node:fs";
|
||||||
|
|
||||||
|
// process.cwd() es /app dentro del contenedor (WORKDIR /app en el Dockerfile),
|
||||||
|
// donde Coolify monta el volumen persistente en /app/data.
|
||||||
|
function createDb() {
|
||||||
|
const dir = path.join(process.cwd(), "data");
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
const db = new Database(path.join(dir, "informe.db"));
|
||||||
|
db.pragma("journal_mode = WAL");
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS metas (
|
||||||
|
email TEXT PRIMARY KEY,
|
||||||
|
monto REAL NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS config (
|
||||||
|
clave TEXT PRIMARY KEY,
|
||||||
|
valor TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS geo_override (
|
||||||
|
opportunity_id TEXT PRIMARY KEY,
|
||||||
|
lat REAL,
|
||||||
|
lon REAL,
|
||||||
|
zona TEXT,
|
||||||
|
depto TEXT
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
const g = globalThis;
|
||||||
|
const db = g.__informeDb ?? (g.__informeDb = createDb());
|
||||||
|
export default db;
|
||||||
239
app/lib/derive.js
Normal file
239
app/lib/derive.js
Normal file
|
|
@ -0,0 +1,239 @@
|
||||||
|
// Cálculos portados de herramientas/sync_pipe.js (ETL estático) — misma lógica, servidor en vivo.
|
||||||
|
|
||||||
|
export const CARTERA = ["Up-Selling", "Cross-Selling", "Plan de Cuenta"];
|
||||||
|
|
||||||
|
export const PESO_PLAN = {
|
||||||
|
"Plan A - En firma": 0.9,
|
||||||
|
"Plan B - En Negociación": 0.6,
|
||||||
|
"Plan C - En seguimiento": 0.3,
|
||||||
|
"Plan D - Recalificar": 0.15,
|
||||||
|
"Sin plan de cierre": 0.1,
|
||||||
|
};
|
||||||
|
export const PLAN_ORDER = Object.keys(PESO_PLAN);
|
||||||
|
|
||||||
|
export function cierreVencido(o) {
|
||||||
|
return !!o.close && o.close < new Date().toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function nomCorto(n) {
|
||||||
|
const p = (n || "").split(" ");
|
||||||
|
return p.length > 2 ? `${p[0]} ${p[p.length - 2]}` : n || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Los 4 tipos que cuentan para cumplimiento de meta (ver CLAUDE.md — se excluyen renovaciones y SAC).
|
||||||
|
export const TIPOS_META = ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling", "Plan de Cuenta"];
|
||||||
|
|
||||||
|
// Ejecutivos de venta reales (ver CLAUDE.md). Gabriela Sánchez y Ashley Bermúdez aparecen
|
||||||
|
// en los datos de Dynamics pero no son ejecutivas de venta — se excluyen del selector.
|
||||||
|
export const EJECUTIVOS_VENTA = [
|
||||||
|
"Mirna Obando Morras",
|
||||||
|
"Maria Auxiliadora Marenco Abea",
|
||||||
|
"Denis Urroz Manzanares",
|
||||||
|
"Daybellys Perez Sequeira",
|
||||||
|
"Martha Somarriba Sirias",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Renovaciones y cohorte NO se filtran a rol 'ventas' — SAC renueva tanto como Ventas (ver
|
||||||
|
// CLAUDE.md). Alcance verificado contra Dynamics: ventas+sac con datos reales en wonRen/pipeRen.
|
||||||
|
export const EJECUTIVOS_RENOV = [
|
||||||
|
"Ashley Bermudez Valverde",
|
||||||
|
"Daybellys Perez Sequeira",
|
||||||
|
"Denis Urroz Manzanares",
|
||||||
|
"Gabriela Sánchez Villareyna",
|
||||||
|
"José Centeno Silva",
|
||||||
|
"Maria Auxiliadora Marenco Abea",
|
||||||
|
"Martha Somarriba Sirias",
|
||||||
|
"Mirna Obando Morras",
|
||||||
|
"Ricardo Silva Ramírez",
|
||||||
|
];
|
||||||
|
|
||||||
|
export function segmentoDe(tipo) {
|
||||||
|
return CARTERA.includes(tipo) ? "Cartera Activa" : "Clientes Nuevos";
|
||||||
|
}
|
||||||
|
|
||||||
|
// El competidor viene con mayúsculas inconsistentes desde el CRM ('Tigo' y 'TIGO' son el mismo).
|
||||||
|
// 'Se Desconoce' y el vacío NO se mezclan: "no sé contra quién compito" y "no lo llené" son cosas
|
||||||
|
// distintas (ver herramientas/sync_pipe.js del sitio HTML, misma tabla de canónicos).
|
||||||
|
const COMP_CANON = {
|
||||||
|
tigo: "Tigo", claro: "Claro", ideay: "Ideay", ufinet: "UFINET", enatrel: "Enatrel",
|
||||||
|
"ibw comunicaciones": "IBW Comunicaciones", starlink: "Starlink", casavision: "CasaVision",
|
||||||
|
alliance: "Alliance", ninguno: "Ninguno", otro: "Otro", "se desconoce": "Se desconoce",
|
||||||
|
};
|
||||||
|
export function normComp(c) {
|
||||||
|
if (!c) return "Sin registrar";
|
||||||
|
return COMP_CANON[c.trim().toLowerCase()] || c.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CLASIF_ORDER = ["Hirviendo", "Caliente", "Cálida", "Tibia", "Fría", "Sin clasificar"];
|
||||||
|
export const CLASIF_COLOR = {
|
||||||
|
Hirviendo: "#B23A2E", Caliente: "#d1642a", "Cálida": "#C98A1B", Tibia: "#5c8fb8",
|
||||||
|
"Fría": "#7f96a8", "Sin clasificar": "#c2ccd6",
|
||||||
|
};
|
||||||
|
const CALIDAD_DE = { Hirviendo: "Alta", Caliente: "Alta", "Cálida": "Media", Tibia: "Baja", "Fría": "Baja" };
|
||||||
|
export const CALIDAD_ORDER = ["Alta", "Media", "Baja", "Sin clasificar"];
|
||||||
|
export const CALIDAD_COLOR = { Alta: "#B23A2E", Media: "#C98A1B", Baja: "#7f96a8", "Sin clasificar": "#c2ccd6" };
|
||||||
|
export function calidadDe(clasif) {
|
||||||
|
return CALIDAD_DE[clasif] || "Sin clasificar";
|
||||||
|
}
|
||||||
|
export function hayClasif(arr) {
|
||||||
|
return arr.some((o) => o.clasif && o.clasif !== "Sin clasificar");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Catálogo cerrado 2026-08-17 (21 objetivos activos, 7 etapas) — ver
|
||||||
|
// Proyectos/Mejoras Dynamics CRM/Actividades en CRM/estado-proyecto-agosto2026.md, replicado tal
|
||||||
|
// cual desde herramientas/build_actividades.js del sitio HTML (no inventar valores nuevos acá).
|
||||||
|
const ETAPAS = [
|
||||||
|
{ etapa: "1. Prospección y calificación", objetivos: ["Prospección", "Calificar Oportunidad"] },
|
||||||
|
{ etapa: "2. Diagnóstico y cierre", objetivos: ["Diagnosticar Necesidades", "Presentación de Servicio", "Presentar Oferta", "Negociación", "Firma Contrato-Adendum"] },
|
||||||
|
{ etapa: "3. Renovación", objetivos: ["Renovación"] },
|
||||||
|
{ etapa: "4. Gestión de cuentas (Mapa de Jugadores)", objetivos: ["Identificar Campeón", "Fortalecer Campeón", "Gestionar Anticampeón"] },
|
||||||
|
{ etapa: "5. Retención y riesgo", objetivos: ["Control de daños", "Retención", "Postventa/Cobro", "Encuestar"] },
|
||||||
|
{ etapa: "6. Actividades específicas de servicio", objetivos: ["Prospectar Vecinos FO", "Reunión Técnica", "Recopilación Proyecto SW"] },
|
||||||
|
{ etapa: "7. Administrativo", objetivos: ["Planificación", "Gestión Admin.", "Otro"] },
|
||||||
|
];
|
||||||
|
export const ETAPA_ORDER = ETAPAS.map((e) => e.etapa);
|
||||||
|
export const OBJETIVO_A_ETAPA = {};
|
||||||
|
ETAPAS.forEach((e) => e.objetivos.forEach((o) => { OBJETIVO_A_ETAPA[o] = e.etapa; }));
|
||||||
|
|
||||||
|
// Campo que ancla el horizonte y el cálculo de Vencida — Cita es un bloque de calendario (importa
|
||||||
|
// CUÁNDO EMPIEZA), Tarea/Llamada son ítems de trabajo con fecha de compromiso (importa PARA CUÁNDO
|
||||||
|
// debían estar listas). Replicado de assets/js/pages/actividades.js del sitio HTML.
|
||||||
|
export function actAncla(a) {
|
||||||
|
return a.tipo === "Cita" ? a.scheduledstart : a.scheduledend || a.scheduledstart;
|
||||||
|
}
|
||||||
|
export function actEstadoFinal(a) {
|
||||||
|
if (a.estado === "completada") return "Completada";
|
||||||
|
if (a.estado === "cancelada") return "Cancelada";
|
||||||
|
const f = actAncla(a);
|
||||||
|
if (!f) return "Pendiente";
|
||||||
|
const anclaDia = new Date(f);
|
||||||
|
anclaDia.setHours(0, 0, 0, 0);
|
||||||
|
const hoy = new Date();
|
||||||
|
hoy.setHours(0, 0, 0, 0);
|
||||||
|
return anclaDia < hoy ? "Vencida" : "Pendiente";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Igual que agg(), pero ordena por un orden declarado (orden) en vez de por frecuencia — para ejes
|
||||||
|
// como Plan de Cierre o Fase, donde el orden natural del negocio importa más que el conteo.
|
||||||
|
export function aggOrd(arr, key, orden, valfn) {
|
||||||
|
return agg(arr, key, valfn).sort((a, b) => {
|
||||||
|
const ia = orden.indexOf(a.k), ib = orden.indexOf(b.k);
|
||||||
|
return (ia === -1 ? 999 : ia) - (ib === -1 ? 999 : ib);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dimensiones conmutables de la matriz de ejecutivos (ExecMatrix) — puerto de MTZ_DIMS
|
||||||
|
// (assets/js/tables.js del sitio HTML). Cada una: `k` (campo de la fila), `lbl` (pestaña),
|
||||||
|
// `orden` (comparador para las columnas) y `corto` (etiqueta corta de columna).
|
||||||
|
// Nota: "Fase" no tiene un orden canónico portado todavía (el HTML normaliza 3 vocabularios de
|
||||||
|
// proceso distintos con FASE_MAP/FASE_ORDER, ver sesion.md — no replicado en Next.js aún), así que
|
||||||
|
// queda ordenada por frecuencia en vez de por el embudo real.
|
||||||
|
export const MTZ_DIMS = [
|
||||||
|
{ k: "plan", lbl: "Plan de Cierre", orden: (a, b) => PLAN_ORDER.indexOf(a) - PLAN_ORDER.indexOf(b), corto: (s) => s.replace("Plan ", "").replace(" - ", " ") },
|
||||||
|
{ k: "prev", lbl: "Categoría Previsión", orden: (a, b) => (parseInt(a, 10) || 0) - (parseInt(b, 10) || 0), corto: (s) => s.replace(/^\d+%\s*/, "") },
|
||||||
|
{ k: "actividad", lbl: "Actividad", orden: (a, b) => ["Activa", "Tibia", "Fría", "Congelada"].indexOf(a) - ["Activa", "Tibia", "Fría", "Congelada"].indexOf(b), corto: (s) => s },
|
||||||
|
{ k: "clasif", lbl: "Temperatura", orden: (a, b) => CLASIF_ORDER.indexOf(a) - CLASIF_ORDER.indexOf(b), corto: (s) => s },
|
||||||
|
{ k: "faseActual", lbl: "Fase", orden: null, corto: (s) => s },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Agrupa arr por o[key], contando y sumando valfn(o). Ordena por conteo descendente.
|
||||||
|
export function agg(arr, key, valfn) {
|
||||||
|
const m = new Map();
|
||||||
|
arr.forEach((o) => {
|
||||||
|
const k = o[key] || "(sin dato)";
|
||||||
|
if (!m.has(k)) m.set(k, { n: 0, v: 0 });
|
||||||
|
const e = m.get(k);
|
||||||
|
e.n++;
|
||||||
|
e.v += valfn ? valfn(o) : 0;
|
||||||
|
});
|
||||||
|
return [...m.entries()].map(([k, x]) => ({ k, ...x })).sort((a, b) => b.n - a.n);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cruce Actividades × Tubería/Previsión — puerto de decorarActividadVentana()/actividadesEnVentana()
|
||||||
|
// (App Informe/assets/js/utils.js). `actividades` viene de getActividades() (queries.js);
|
||||||
|
// `ini`/`fin` acotan la ventana de fechas (abierta para Tubería, el mes/atrasadas para Previsión).
|
||||||
|
// A diferencia del HTML no muta in-place — devuelve un array nuevo (más idiomático en Server
|
||||||
|
// Components).
|
||||||
|
export function decorarActividadVentana(arr, actividades, ini, fin) {
|
||||||
|
const m = new Map();
|
||||||
|
(actividades || []).forEach((a) => {
|
||||||
|
if (a.estado === "cancelada" || !a.referente || a.referente.tipo !== "opportunity" || !a.scheduledstart) return;
|
||||||
|
const f = a.scheduledstart.slice(0, 10);
|
||||||
|
if (f < ini || f > fin) return;
|
||||||
|
if (!m.has(a.referente.id) || f < m.get(a.referente.id)) m.set(a.referente.id, f);
|
||||||
|
});
|
||||||
|
return arr.map((o) => {
|
||||||
|
const f = m.get(o.id) || null;
|
||||||
|
return { ...o, actFecha: f, actAgendada: f ? "Con actividad agendada" : "Sin actividad agendada" };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export const ACTAGENDADA_ORDEN = ["Con actividad agendada", "Sin actividad agendada"];
|
||||||
|
|
||||||
|
// Agrupa ganadas+perdidas por una dimensión y adjunta el motivo de pérdida más frecuente de cada
|
||||||
|
// categoría — puerto de catsWonLost() (App Informe/assets/js/tables.js), para comparePanelMotivo.
|
||||||
|
// wonVal/lostVal: por defecto MRR realmente cobrado (won.actual) vs. estimado perdido (lost.est) —
|
||||||
|
// mismo criterio que "Ventas Ganadas"/"Por qué Perdemos".
|
||||||
|
export function catsWonLost(wonArr, lostArr, key, wonVal = (o) => o.actual || 0, lostVal = (o) => o.est || 0) {
|
||||||
|
const keys = [...new Set([...wonArr.map((o) => o[key]), ...lostArr.map((o) => o[key])].filter(Boolean))];
|
||||||
|
return keys
|
||||||
|
.map((k) => {
|
||||||
|
const g = wonArr.filter((o) => o[key] === k);
|
||||||
|
const l = lostArr.filter((o) => o[key] === k);
|
||||||
|
// Excluye "Descartada sin motivo (depuración)" del ranking — es higiene de datos, no una
|
||||||
|
// razón de negocio real que explique la pérdida (ver CLAUDE.md).
|
||||||
|
const mm = {};
|
||||||
|
l.forEach((o) => {
|
||||||
|
if (o.motivo && o.motivo !== "Descartada sin motivo (depuración)") mm[o.motivo] = (mm[o.motivo] || 0) + 1;
|
||||||
|
});
|
||||||
|
const top = Object.entries(mm).sort((a, b) => b[1] - a[1])[0];
|
||||||
|
const depu = l.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||||
|
return {
|
||||||
|
k,
|
||||||
|
ganaN: g.length,
|
||||||
|
ganaV: g.reduce((s, o) => s + wonVal(o), 0),
|
||||||
|
pierdeN: l.length,
|
||||||
|
pierdeV: l.reduce((s, o) => s + lostVal(o), 0),
|
||||||
|
topMotivo: top ? top[0] : null,
|
||||||
|
topMotivoN: top ? top[1] : 0,
|
||||||
|
depu,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((c) => c.ganaN || c.pierdeN)
|
||||||
|
.sort((a, b) => b.ganaN + b.pierdeN - (a.ganaN + a.pierdeN));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bucketActividad(diasSinActividad) {
|
||||||
|
if (diasSinActividad == null) return "Sin dato";
|
||||||
|
if (diasSinActividad <= 14) return "Activa";
|
||||||
|
if (diasSinActividad <= 30) return "Tibia";
|
||||||
|
if (diasSinActividad <= 60) return "Fría";
|
||||||
|
return "Congelada";
|
||||||
|
}
|
||||||
|
|
||||||
|
// row: objeto ya con etiquetas resueltas (tipo, plan como texto, no option-set numérico).
|
||||||
|
// faseInfo: { fase, started } | undefined, de alfa_stagedurations.
|
||||||
|
// today: Date, para calcular días en fase de forma determinística.
|
||||||
|
export function derivePipelineRow(row, faseInfo, today) {
|
||||||
|
const plan = row.plan || "Sin plan de cierre";
|
||||||
|
const peso = PESO_PLAN[plan] ?? 0.1;
|
||||||
|
const est = row.est || 0;
|
||||||
|
const diasEnFase = faseInfo?.started
|
||||||
|
? Math.round((today - new Date(faseInfo.started)) / 86400000)
|
||||||
|
: null;
|
||||||
|
const estanc = (row.dsa != null && row.dsa > 14) || (diasEnFase != null && diasEnFase > 30);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...row,
|
||||||
|
plan,
|
||||||
|
peso,
|
||||||
|
fc: +(est * peso).toFixed(2),
|
||||||
|
estanc,
|
||||||
|
faseActual: faseInfo?.fase || null,
|
||||||
|
diasEnFase,
|
||||||
|
actividad: bucketActividad(row.dsa),
|
||||||
|
segmento: segmentoDe(row.tipo),
|
||||||
|
calidad: calidadDe(row.clasif),
|
||||||
|
mov: estanc ? "Estancada" : "En movimiento",
|
||||||
|
mesCierre: row.close ? row.close.slice(0, 7) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
54
app/lib/filterState.js
Normal file
54
app/lib/filterState.js
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
// Estado de filtro multi-dimensión, codificado en el searchParam `f` como `dim:valor,dim2:valor2`
|
||||||
|
// (equivalente al objeto global `filt` de App Informe/assets/js/state.js). Se parsea/filtra en el
|
||||||
|
// servidor; los componentes cliente (FilterableRow, FilterChips) solo arman la URL nueva.
|
||||||
|
|
||||||
|
const SEP_DIM = ",";
|
||||||
|
const SEP_KV = ":";
|
||||||
|
|
||||||
|
// Nota: NO se usa encodeURIComponent acá — URLSearchParams ya percent-codifica el valor completo
|
||||||
|
// del param `f` al armar la query string (y lo decodifica solo al leerlo con .get()). Codificar acá
|
||||||
|
// además duplicaría el escapado ("%3A" -> "%253A"). Limitación aceptada: un valor de campo que
|
||||||
|
// contenga literalmente "," o ":" rompería el parseo — ningún dato real de ALFA+ los usa hoy.
|
||||||
|
export function parseFiltParam(f) {
|
||||||
|
const filt = {};
|
||||||
|
if (!f) return filt;
|
||||||
|
for (const part of f.split(SEP_DIM)) {
|
||||||
|
const i = part.indexOf(SEP_KV);
|
||||||
|
if (i === -1) continue;
|
||||||
|
const dim = part.slice(0, i);
|
||||||
|
const val = part.slice(i + 1);
|
||||||
|
if (dim && val) filt[dim] = val;
|
||||||
|
}
|
||||||
|
return filt;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeFiltParam(filt) {
|
||||||
|
const entries = Object.entries(filt).filter(([, v]) => v);
|
||||||
|
if (!entries.length) return "";
|
||||||
|
return entries.map(([k, v]) => `${k}${SEP_KV}${v}`).join(SEP_DIM);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mismo criterio AND que pipeF() del sitio HTML: cada dimensión filtrada exige igualdad exacta.
|
||||||
|
// "(sin dato)" (el bucket que agg() usa para valores vacíos) matchea contra o[dim] vacío/null.
|
||||||
|
export function applyFilt(arr, filt) {
|
||||||
|
const entries = Object.entries(filt);
|
||||||
|
if (!entries.length) return arr;
|
||||||
|
return arr.filter((o) => entries.every(([dim, val]) => (o[dim] || "(sin dato)") === val));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle de uno o varios ejes a la vez (una fila de panel = 1 par, una celda de matriz = 2 pares).
|
||||||
|
// Si TODOS los pares ya están activos, el clic los quita; si no, los fija todos de golpe (mismo
|
||||||
|
// comportamiento "todo o nada" que bindRows()/bindMatriz*() del HTML).
|
||||||
|
export function toggleFilt(filt, pairs) {
|
||||||
|
const allActive = pairs.every(([dim, val]) => filt[dim] === val);
|
||||||
|
const next = { ...filt };
|
||||||
|
pairs.forEach(([dim, val]) => {
|
||||||
|
if (allActive) delete next[dim];
|
||||||
|
else next[dim] = val;
|
||||||
|
});
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isFiltActive(filt, pairs) {
|
||||||
|
return pairs.every(([dim, val]) => filt[dim] === val);
|
||||||
|
}
|
||||||
34
app/lib/metas.js
Normal file
34
app/lib/metas.js
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
import db from "./db";
|
||||||
|
|
||||||
|
// Metas mensuales — SQLite (Etapa 4). Clave: correo del vendedor, resuelto en vivo
|
||||||
|
// contra systemusers (no hay una lista fija de correos confirmados — ver migration.md §11.5).
|
||||||
|
// La tabla arranca vacía: un administrador las carga desde /admin/metas.
|
||||||
|
|
||||||
|
export function getMetas() {
|
||||||
|
const rows = db.prepare("SELECT email, monto FROM metas").all();
|
||||||
|
const map = {};
|
||||||
|
rows.forEach((r) => {
|
||||||
|
map[r.email] = r.monto;
|
||||||
|
});
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMetaGlobal() {
|
||||||
|
const row = db.prepare("SELECT valor FROM config WHERE clave = 'meta_global'").get();
|
||||||
|
if (row) return Number(row.valor);
|
||||||
|
return Object.values(getMetas()).reduce((a, v) => a + v, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setMeta(email, monto) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO metas (email, monto, updated_at) VALUES (?, ?, datetime('now'))
|
||||||
|
ON CONFLICT(email) DO UPDATE SET monto = excluded.monto, updated_at = excluded.updated_at`
|
||||||
|
).run(email.toLowerCase(), monto);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setMetaGlobal(monto) {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO config (clave, valor) VALUES ('meta_global', ?)
|
||||||
|
ON CONFLICT(clave) DO UPDATE SET valor = excluded.valor`
|
||||||
|
).run(String(monto));
|
||||||
|
}
|
||||||
362
app/lib/queries.js
Normal file
362
app/lib/queries.js
Normal file
|
|
@ -0,0 +1,362 @@
|
||||||
|
import { dv, fv, lookupType, odataString } from "./dataverse";
|
||||||
|
import { derivePipelineRow, segmentoDe, normComp, EJECUTIVOS_VENTA, OBJETIVO_A_ETAPA } from "./derive";
|
||||||
|
|
||||||
|
const OPP_SELECT = [
|
||||||
|
"opportunityid",
|
||||||
|
"name",
|
||||||
|
"_ownerid_value",
|
||||||
|
"alfa_typeopportunity",
|
||||||
|
"alfa_tipodeventa",
|
||||||
|
"_alfa_lineadenegocioid_value",
|
||||||
|
"_alfa_servicioproductoid_value",
|
||||||
|
"estimatedvalue",
|
||||||
|
"actualvalue",
|
||||||
|
"alfa_plandecierre",
|
||||||
|
"alfa_envejecimiento",
|
||||||
|
"alfa_diassinactividad",
|
||||||
|
"estimatedclosedate",
|
||||||
|
"actualclosedate",
|
||||||
|
"stepname",
|
||||||
|
"alfa_estadodelanegociacion",
|
||||||
|
"_customerid_value",
|
||||||
|
"_campaignid_value",
|
||||||
|
"_alfa_competidorid_value",
|
||||||
|
"alfa_puntuaciondelaoportunidad",
|
||||||
|
"alfa_niveldeoportunidadestrellas",
|
||||||
|
"alfa_clasificaciondeoportunidad",
|
||||||
|
"alfa_luzamarilla",
|
||||||
|
"msdyn_forecastcategory",
|
||||||
|
].join(",");
|
||||||
|
|
||||||
|
// Tubería: 5 tipos de la cartera "en pipeline" (ver ALFA_Estructura_Oportunidades_CRM.md).
|
||||||
|
const PIPE_TYPE_FILTER =
|
||||||
|
"(alfa_typeopportunity eq 100000000 or alfa_typeopportunity eq 100000003 or " +
|
||||||
|
"alfa_typeopportunity eq 100000004 or alfa_typeopportunity eq 100000007 or alfa_typeopportunity eq 100000009)";
|
||||||
|
|
||||||
|
// Renovaciones: Contrato Vencido (100000002) y Próximo a Vencer 30/60/90 (100000001) — universo
|
||||||
|
// aparte de Ventas, no cuenta para cumplimiento de meta (ver CLAUDE.md).
|
||||||
|
const REN_TYPE_FILTER = "(alfa_typeopportunity eq 100000001 or alfa_typeopportunity eq 100000002)";
|
||||||
|
|
||||||
|
function chunk(arr, size) {
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSystemUsers(accessToken) {
|
||||||
|
const data = await dv(
|
||||||
|
"systemusers?$select=systemuserid,fullname,internalemailaddress&$filter=isdisabled eq false",
|
||||||
|
accessToken
|
||||||
|
);
|
||||||
|
return (data.value || []).map((u) => ({
|
||||||
|
id: u.systemuserid,
|
||||||
|
name: u.fullname,
|
||||||
|
email: (u.internalemailaddress || "").toLowerCase(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resolveOwnerId(email, accessToken) {
|
||||||
|
if (!email) return null;
|
||||||
|
const data = await dv(
|
||||||
|
`systemusers?$select=systemuserid&$filter=${encodeURIComponent(
|
||||||
|
`internalemailaddress eq '${odataString(email)}'`
|
||||||
|
)}`,
|
||||||
|
accessToken
|
||||||
|
);
|
||||||
|
return data.value?.[0]?.systemuserid || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapOpportunityRow(o) {
|
||||||
|
const tipo = fv(o, "alfa_typeopportunity");
|
||||||
|
return {
|
||||||
|
id: o.opportunityid,
|
||||||
|
name: o.name,
|
||||||
|
owner: fv(o, "_ownerid_value"),
|
||||||
|
tipo,
|
||||||
|
segmento: segmentoDe(tipo),
|
||||||
|
origen: fv(o, "alfa_tipodeventa"),
|
||||||
|
linea: fv(o, "_alfa_lineadenegocioid_value"),
|
||||||
|
servicio: fv(o, "_alfa_servicioproductoid_value"),
|
||||||
|
est: o.estimatedvalue || 0,
|
||||||
|
actual: o.actualvalue || 0,
|
||||||
|
plan: fv(o, "alfa_plandecierre"),
|
||||||
|
env: o.alfa_envejecimiento ?? null,
|
||||||
|
dsa: o.alfa_diassinactividad ?? null,
|
||||||
|
close: o.estimatedclosedate ? o.estimatedclosedate.slice(0, 10) : null,
|
||||||
|
actualClose: o.actualclosedate ? o.actualclosedate.slice(0, 10) : null,
|
||||||
|
step: o.stepname,
|
||||||
|
estado: o.alfa_estadodelanegociacion || null,
|
||||||
|
cliente: fv(o, "_customerid_value"),
|
||||||
|
campaign: fv(o, "_campaignid_value"),
|
||||||
|
score: o.alfa_puntuaciondelaoportunidad ?? null,
|
||||||
|
estrellas: o.alfa_niveldeoportunidadestrellas ?? null,
|
||||||
|
clasif: fv(o, "alfa_clasificaciondeoportunidad") || "Sin clasificar",
|
||||||
|
luz: fv(o, "alfa_luzamarilla") || "Sin registrar",
|
||||||
|
competidor: normComp(fv(o, "_alfa_competidorid_value")),
|
||||||
|
// Escala propia de ALFA+ (NO el forecastcategory estándar de Dynamics — ver CLAUDE.md):
|
||||||
|
// la etiqueta ya trae el % adelante ("20% Calificada" … "90% Firma de contrato"), de ahí se
|
||||||
|
// deriva el orden sin mantener un mapa aparte.
|
||||||
|
prev: fv(o, "msdyn_forecastcategory") || "Sin categoría",
|
||||||
|
prevPct: parseInt(fv(o, "msdyn_forecastcategory") || "", 10) || 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getFaseActual(oppIds, accessToken) {
|
||||||
|
const fase = {};
|
||||||
|
for (const batch of chunk(oppIds, 150)) {
|
||||||
|
if (!batch.length) continue;
|
||||||
|
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
|
||||||
|
const fetchXml =
|
||||||
|
`<fetch><entity name="alfa_stageduration">` +
|
||||||
|
`<attribute name="alfa_subject"/><attribute name="alfa_started"/><attribute name="alfa_opportunity"/>` +
|
||||||
|
`<filter><condition attribute="statuscode" operator="eq" value="1"/>` +
|
||||||
|
`<condition attribute="alfa_opportunity" operator="in">${conditions}</condition></filter>` +
|
||||||
|
`</entity></fetch>`;
|
||||||
|
const data = await dv(`alfa_stagedurations?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
|
||||||
|
for (const r of data.value || []) {
|
||||||
|
const oid = r["_alfa_opportunity_value"] || r.alfa_opportunity;
|
||||||
|
const started = r.alfa_started;
|
||||||
|
const subj = (r.alfa_subject || "").replace("Fase: ", "");
|
||||||
|
if (!fase[oid] || (started && started > fase[oid].started)) {
|
||||||
|
fase[oid] = { fase: subj, started };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fase;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Motivo/competidor de cierre — viven en opportunityclose, no en opportunity (ver
|
||||||
|
// contexto_tabla_cierre_oportunidad.md). alfa_motivodecierre es el campo principal (Alfa);
|
||||||
|
// opportunitystatuscode es el respaldo estándar — en la práctica muchos cierres recientes
|
||||||
|
// solo llenan el estándar. Nos quedamos con el cierre más reciente por oportunidad.
|
||||||
|
export async function getMotivosCierre(oppIds, accessToken) {
|
||||||
|
const motivos = {};
|
||||||
|
for (const batch of chunk(oppIds, 150)) {
|
||||||
|
if (!batch.length) continue;
|
||||||
|
const conditions = batch.map((id) => `<value>${id}</value>`).join("");
|
||||||
|
const fetchXml =
|
||||||
|
`<fetch><entity name="opportunityclose">` +
|
||||||
|
`<attribute name="opportunityid"/><attribute name="alfa_motivodecierre"/>` +
|
||||||
|
`<attribute name="opportunitystatuscode"/><attribute name="alfa_competitor"/>` +
|
||||||
|
`<attribute name="createdon"/>` +
|
||||||
|
`<filter><condition attribute="opportunityid" operator="in">${conditions}</condition></filter>` +
|
||||||
|
`</entity></fetch>`;
|
||||||
|
const data = await dv(`opportunitycloses?fetchXml=${encodeURIComponent(fetchXml)}`, accessToken);
|
||||||
|
for (const r of data.value || []) {
|
||||||
|
const oid = r["_opportunityid_value"];
|
||||||
|
const created = r.createdon;
|
||||||
|
if (motivos[oid] && motivos[oid].createdon >= created) continue;
|
||||||
|
motivos[oid] = {
|
||||||
|
createdon: created,
|
||||||
|
motivo: fv(r, "alfa_motivodecierre") || fv(r, "opportunitystatuscode") || null,
|
||||||
|
competidor: fv(r, "_alfa_competitor_value"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return motivos;
|
||||||
|
}
|
||||||
|
|
||||||
|
// scope: { email, locked } de ownerFilter(). email null (admin, "todos") no filtra por propietario.
|
||||||
|
// typeFilter: PIPE_TYPE_FILTER (ventas, default) o REN_TYPE_FILTER (renovaciones).
|
||||||
|
async function getPipelineOfType(accessToken, scope, typeFilter) {
|
||||||
|
let filter = `statecode eq 0 and estimatedclosedate ne null and msdyn_forecastcategory ne 100000001 and ${typeFilter}`;
|
||||||
|
if (scope.email) {
|
||||||
|
const ownerId = await resolveOwnerId(scope.email, accessToken);
|
||||||
|
if (!ownerId) return [];
|
||||||
|
filter += ` and _ownerid_value eq ${ownerId}`;
|
||||||
|
}
|
||||||
|
const data = await dv(
|
||||||
|
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
|
||||||
|
accessToken
|
||||||
|
);
|
||||||
|
const rows = (data.value || []).map(mapOpportunityRow);
|
||||||
|
const faseMap = await getFaseActual(rows.map((r) => r.id), accessToken);
|
||||||
|
const today = new Date();
|
||||||
|
return rows.map((r) => derivePipelineRow(r, faseMap[r.id], today));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPipeline(accessToken, scope) {
|
||||||
|
return getPipelineOfType(accessToken, scope, PIPE_TYPE_FILTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRenovPipeline(accessToken, scope) {
|
||||||
|
return getPipelineOfType(accessToken, scope, REN_TYPE_FILTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resuelve una sola vez el systemuserid del scope (o null si no aplica) — para reusar en varias
|
||||||
|
// llamadas a getClosed sin repetir la consulta a systemusers cada vez (ej. Tendencia, 6 meses).
|
||||||
|
export async function resolveScopeOwnerId(scope, accessToken) {
|
||||||
|
if (!scope.email) return { none: true };
|
||||||
|
const ownerId = await resolveOwnerId(scope.email, accessToken);
|
||||||
|
return { none: false, ownerId };
|
||||||
|
}
|
||||||
|
|
||||||
|
// statecode: 1 = ganadas, 2 = perdidas. month: "YYYY-MM", filtra por el mes de cierre real.
|
||||||
|
// ownerId: opcional, ya resuelto vía resolveScopeOwnerId — evita resolver el email en cada llamada.
|
||||||
|
// typeFilter: opcional — sin él, trae cualquier tipo (Ventas ganadas/perdidas ya filtran por owner
|
||||||
|
// de rol 'ventas' en la página; Renovaciones pasa REN_TYPE_FILTER explícito).
|
||||||
|
export async function getClosed(accessToken, scope, statecode, month, resolvedOwnerId, typeFilter) {
|
||||||
|
const monthStart = `${month}-01`;
|
||||||
|
const [y, m] = month.split("-").map(Number);
|
||||||
|
const nextMonth = new Date(y, m, 1).toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
let filter =
|
||||||
|
`statecode eq ${statecode} and actualclosedate ge ${monthStart} and actualclosedate lt ${nextMonth}`;
|
||||||
|
if (typeFilter) filter += ` and ${typeFilter}`;
|
||||||
|
if (scope.email) {
|
||||||
|
const ownerId = resolvedOwnerId !== undefined ? resolvedOwnerId : await resolveOwnerId(scope.email, accessToken);
|
||||||
|
if (!ownerId) return [];
|
||||||
|
filter += ` and _ownerid_value eq ${ownerId}`;
|
||||||
|
}
|
||||||
|
const data = await dv(
|
||||||
|
`opportunities?$select=${OPP_SELECT}&$filter=${encodeURIComponent(filter)}&$top=1000`,
|
||||||
|
accessToken
|
||||||
|
);
|
||||||
|
return (data.value || []).map(mapOpportunityRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRenovClosed(accessToken, scope, statecode, month, resolvedOwnerId) {
|
||||||
|
return getClosed(accessToken, scope, statecode, month, resolvedOwnerId, REN_TYPE_FILTER);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ventana de historia para Actividades: statecode eq 0 (abierta, sin tope — es un plan de trabajo
|
||||||
|
// vivo) trae todo lo pendiente; scheduledend ge <cutoff> acota lo cerrado/cancelado a los últimos
|
||||||
|
// 90 días para no traer años de historial en cada carga (mismo patrón que build_actividades.js del
|
||||||
|
// sitio HTML, que usa un corte de fecha fijo en vez de "siempre todo").
|
||||||
|
const ACTIVIDADES_DIAS_HISTORIA = 90;
|
||||||
|
|
||||||
|
const ACTIVIDAD_ENTIDADES = [
|
||||||
|
{ entity: "tasks", tipo: "Tarea", navProp: "regardingobjectid_opportunity_task", propioField: "prioritycode", propioLabel: "Prioridad" },
|
||||||
|
{ entity: "appointments", tipo: "Cita", navProp: "regardingobjectid_opportunity_appointment", propioField: "location", propioLabel: "Ubicación" },
|
||||||
|
{ entity: "phonecalls", tipo: "Llamada", navProp: "regardingobjectid_opportunity_phonecall", propioField: "directioncode", propioLabel: "Dirección" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function estadoBase(statecode) {
|
||||||
|
if (statecode === 1) return "completada";
|
||||||
|
if (statecode === 2) return "cancelada";
|
||||||
|
return "abierta"; // 0=Abierto, 3=Programado (Cita) — ambas "no cerradas" a efectos de negocio
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapActividadRow(r, tipo, navProp, propioField, propioLabel) {
|
||||||
|
const tipoRef = lookupType(r, "_regardingobjectid_value");
|
||||||
|
const nombreRef = fv(r, "_regardingobjectid_value");
|
||||||
|
const objetivo = fv(r, "_alfa_objetivodeactividad_value");
|
||||||
|
const opp = r[navProp];
|
||||||
|
const propioValor = propioField === "location" ? r.location || null : fv(r, propioField);
|
||||||
|
return {
|
||||||
|
id: r.activityid,
|
||||||
|
tipo,
|
||||||
|
owner: fv(r, "_ownerid_value"),
|
||||||
|
asunto: r.subject || "(sin asunto)",
|
||||||
|
scheduledstart: r.scheduledstart || null,
|
||||||
|
scheduledend: r.scheduledend || null,
|
||||||
|
scheduledstartFmt: fv(r, "scheduledstart"),
|
||||||
|
scheduledendFmt: fv(r, "scheduledend"),
|
||||||
|
estado: estadoBase(r.statecode),
|
||||||
|
objetivo,
|
||||||
|
etapa: objetivo ? OBJETIVO_A_ETAPA[objetivo] || null : null,
|
||||||
|
referente: tipoRef && nombreRef ? { tipo: tipoRef, nombre: nombreRef, id: r._regardingobjectid_value } : null,
|
||||||
|
campoPropio: { label: propioLabel, valor: propioValor },
|
||||||
|
ingresoEstimado: opp && typeof opp.estimatedvalue === "number" ? opp.estimatedvalue : null,
|
||||||
|
tipoOportunidad: opp ? fv(opp, "alfa_typeopportunity") : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// scope: { email, locked }. email null (admin, "todos") trae los ejecutivos de venta curados —
|
||||||
|
// mismo alcance que el resto del informe (EJECUTIVOS_VENTA), resuelto en vivo contra systemusers
|
||||||
|
// en vez de una tabla fija de GUID (que es lo que hacía el ETL estático y quedaba desactualizada).
|
||||||
|
const COHORTE_SELECT = [
|
||||||
|
"opportunityid", "name", "createdon", "statecode", "actualclosedate", "estimatedclosedate",
|
||||||
|
"alfa_typeopportunity", "alfa_tipodeventa", "_ownerid_value", "_customerid_value",
|
||||||
|
"_alfa_lineadenegocioid_value", "_campaignid_value", "estimatedvalue", "actualvalue",
|
||||||
|
].join(",");
|
||||||
|
|
||||||
|
function mapCohorteRow(o) {
|
||||||
|
const tipo = fv(o, "alfa_typeopportunity");
|
||||||
|
const creada = o.createdon ? o.createdon.slice(0, 10) : null;
|
||||||
|
const estado = o.statecode === 1 ? "Ganada" : o.statecode === 2 ? "Perdida" : "Abierta";
|
||||||
|
const cierre = o.actualclosedate ? o.actualclosedate.slice(0, 10) : null;
|
||||||
|
const hoy = new Date().toISOString().slice(0, 10);
|
||||||
|
const diasEntre = (a, b) => (a && b ? Math.round((new Date(b) - new Date(a)) / 86400000) : null);
|
||||||
|
return {
|
||||||
|
id: o.opportunityid,
|
||||||
|
name: o.name,
|
||||||
|
owner: fv(o, "_ownerid_value"),
|
||||||
|
cliente: fv(o, "_customerid_value"),
|
||||||
|
creada,
|
||||||
|
mesCohorte: creada ? creada.slice(0, 7) : null,
|
||||||
|
estado,
|
||||||
|
cierre,
|
||||||
|
tipo,
|
||||||
|
segmento: segmentoDe(tipo),
|
||||||
|
origen: fv(o, "alfa_tipodeventa"),
|
||||||
|
linea: fv(o, "_alfa_lineadenegocioid_value"),
|
||||||
|
campaign: fv(o, "_campaignid_value"),
|
||||||
|
est: o.estimatedvalue || 0,
|
||||||
|
val: o.actualvalue || 0,
|
||||||
|
diasACierre: estado !== "Abierta" ? diasEntre(creada, cierre) : null,
|
||||||
|
diasAbierta: estado === "Abierta" ? diasEntre(creada, hoy) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// scope: { email, locked }. mesesAtras: ventana de creación — el sitio HTML deja elegir el rango;
|
||||||
|
// acá se fija a 6 meses para acotar el volumen de la consulta en vivo (createdon no tiene índice
|
||||||
|
// de "top N recientes" propio, así que sin tope esto podría traer años de historial).
|
||||||
|
export async function getCohorte(accessToken, scope, mesesAtras = 6) {
|
||||||
|
const desde = new Date();
|
||||||
|
desde.setMonth(desde.getMonth() - mesesAtras);
|
||||||
|
desde.setDate(1);
|
||||||
|
const filterDesde = desde.toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
let filter = `createdon ge ${filterDesde}`;
|
||||||
|
if (scope.email) {
|
||||||
|
const ownerId = await resolveOwnerId(scope.email, accessToken);
|
||||||
|
if (!ownerId) return [];
|
||||||
|
filter += ` and _ownerid_value eq ${ownerId}`;
|
||||||
|
}
|
||||||
|
const data = await dv(
|
||||||
|
`opportunities?$select=${COHORTE_SELECT}&$filter=${encodeURIComponent(filter)}&$top=5000`,
|
||||||
|
accessToken
|
||||||
|
);
|
||||||
|
return (data.value || []).map(mapCohorteRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
// roster: lista de nombres a incluir cuando no hay un solo propietario en `scope` (default
|
||||||
|
// EJECUTIVOS_VENTA) — Renovaciones pasa EJECUTIVOS_RENOV (Ventas + SAC, ver CLAUDE.md) para no
|
||||||
|
// perderse las actividades de SAC en el cruce "¿Ya se agendó algo?".
|
||||||
|
export async function getActividades(accessToken, scope, roster = EJECUTIVOS_VENTA) {
|
||||||
|
let ownerIds;
|
||||||
|
if (scope.email) {
|
||||||
|
const id = await resolveOwnerId(scope.email, accessToken);
|
||||||
|
if (!id) return [];
|
||||||
|
ownerIds = [id];
|
||||||
|
} else {
|
||||||
|
const users = await getSystemUsers(accessToken);
|
||||||
|
ownerIds = users.filter((u) => roster.includes(u.name)).map((u) => u.id);
|
||||||
|
}
|
||||||
|
if (!ownerIds.length) return [];
|
||||||
|
|
||||||
|
const cutoff = new Date(Date.now() - ACTIVIDADES_DIAS_HISTORIA * 86400000).toISOString().slice(0, 10);
|
||||||
|
const ownerFilterStr = `(${ownerIds.map((id) => `_ownerid_value eq ${id}`).join(" or ")})`;
|
||||||
|
const filter = `(statecode eq 0 or scheduledend ge ${cutoff}) and ${ownerFilterStr}`;
|
||||||
|
|
||||||
|
const results = await Promise.all(
|
||||||
|
ACTIVIDAD_ENTIDADES.map(async ({ entity, tipo, navProp, propioField, propioLabel }) => {
|
||||||
|
// actualend/statuscode salieron del $select: se traían pero nada en la UI los lee — menos
|
||||||
|
// columnas por fila, Dataverse arma la respuesta más rápido (3 consultas en paralelo con
|
||||||
|
// $expand, la página más pesada de la app).
|
||||||
|
const select = [
|
||||||
|
"activityid", "subject", "scheduledstart", "scheduledend",
|
||||||
|
"statecode", "_ownerid_value", "_regardingobjectid_value",
|
||||||
|
"_alfa_objetivodeactividad_value", propioField,
|
||||||
|
];
|
||||||
|
const query =
|
||||||
|
`${entity}?$select=${select.join(",")}` +
|
||||||
|
`&$expand=${navProp}($select=estimatedvalue,alfa_typeopportunity)` +
|
||||||
|
`&$filter=${encodeURIComponent(filter)}&$top=5000`;
|
||||||
|
const data = await dv(query, accessToken);
|
||||||
|
return (data.value || []).map((r) => mapActividadRow(r, tipo, navProp, propioField, propioLabel));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return results.flat();
|
||||||
|
}
|
||||||
4
app/loading.js
Normal file
4
app/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "./components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
4
app/nuevas/loading.js
Normal file
4
app/nuevas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
304
app/nuevas/page.js
Normal file
304
app/nuevas/page.js
Normal file
|
|
@ -0,0 +1,304 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getCohorte, getSystemUsers } from "../lib/queries";
|
||||||
|
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import Panel from "../components/pipeline/Panel";
|
||||||
|
import FilterChips from "../components/FilterChips";
|
||||||
|
import CohMatriz from "../components/nuevas/CohMatriz";
|
||||||
|
import { DYN, money, money2 } from "../lib/constants";
|
||||||
|
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const COH_DIMS = [
|
||||||
|
{ k: "owner", lbl: "Ejecutivo" },
|
||||||
|
{ k: "origen", lbl: "Origen" },
|
||||||
|
{ k: "tipo", lbl: "Tipo de oportunidad" },
|
||||||
|
{ k: "linea", lbl: "Línea de negocio" },
|
||||||
|
{ k: "campaign", lbl: "Campaña" },
|
||||||
|
];
|
||||||
|
const COH_METRICAS = [
|
||||||
|
{ k: "pct", lbl: "% Ganada", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Ganada").length / a.length) * 100) : null) },
|
||||||
|
{ k: "pctP", lbl: "% Perdida", rgb: "178,58,46", fmt: (v) => (v == null ? "—" : `${v}%`), calc: (a) => (a.length ? Math.round((a.filter((o) => o.estado === "Perdida").length / a.length) * 100) : null) },
|
||||||
|
{ k: "n", lbl: "Creadas", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : `${v}`), calc: (a) => a.length || null },
|
||||||
|
{ k: "mrr", lbl: "MRR ganado", rgb: "30,113,184", fmt: (v) => (v == null ? "—" : money(v)), calc: (a) => { const s = a.filter((o) => o.estado === "Ganada").reduce((x, o) => x + o.val, 0); return a.length ? s : null; } },
|
||||||
|
];
|
||||||
|
const DIM_LABELS = { owner: "Ejecutivo", origen: "Origen", tipo: "Tipo", linea: "Línea", campaign: "Campaña" };
|
||||||
|
|
||||||
|
const MESLBL = {
|
||||||
|
"01": "Ene", "02": "Feb", "03": "Mar", "04": "Abr", "05": "May", "06": "Jun",
|
||||||
|
"07": "Jul", "08": "Ago", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dic",
|
||||||
|
};
|
||||||
|
const mesLbl = (m) => (m ? `${MESLBL[m.slice(5, 7)] || m.slice(5, 7)} ${m.slice(0, 4)}` : "—");
|
||||||
|
const COH_TIPOS = {
|
||||||
|
venta: { lbl: "Venta y expansión", tipos: ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling", "Plan de Cuenta"] },
|
||||||
|
renov: { lbl: "Renovaciones", tipos: ["Contrato vencido", "Próximo a Vencer en 30/60/90"] },
|
||||||
|
todas: { lbl: "Todas", tipos: null },
|
||||||
|
};
|
||||||
|
const ESTADOS = [
|
||||||
|
{ k: "Ganada", color: "var(--gana)" },
|
||||||
|
{ k: "Perdida", color: "var(--pierde)" },
|
||||||
|
{ k: "Abierta", color: "#788a9b" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function BarraCohorte({ mes, rows }) {
|
||||||
|
const tot = rows.length || 1;
|
||||||
|
return (
|
||||||
|
<div className="row" style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
|
||||||
|
<span style={{ width: 70, fontSize: 12 }}>{mesLbl(mes)}</span>
|
||||||
|
<div style={{ flex: 1, display: "flex", height: 22, borderRadius: 4, overflow: "hidden", background: "#eef2f5" }}>
|
||||||
|
{ESTADOS.map(({ k, color }) => {
|
||||||
|
const n = rows.filter((o) => o.estado === k).length;
|
||||||
|
if (!n) return null;
|
||||||
|
const pct = (n / tot) * 100;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={k}
|
||||||
|
title={`${k}: ${n} de ${rows.length} (${Math.round(pct)}%)`}
|
||||||
|
style={{
|
||||||
|
width: `${pct}%`, background: color, display: "flex", alignItems: "center",
|
||||||
|
justifyContent: "center", color: "#fff", fontSize: 11, fontWeight: 700,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{pct > 11 ? `${n} (${Math.round(pct)}%)` : ""}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<span style={{ width: 36, textAlign: "right", fontSize: 12 }}>{rows.length}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function NuevasPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner, tipos: tiposParam } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const cohTipos = COH_TIPOS[tiposParam] ? tiposParam : "venta";
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
const cohd = COH_DIMS.some((d) => d.k === sp.cohd) ? sp.cohd : "owner";
|
||||||
|
const cohm = COH_METRICAS.some((m) => m.k === sp.cohm) ? sp.cohm : "pct";
|
||||||
|
|
||||||
|
let arrAll, allUsers;
|
||||||
|
try {
|
||||||
|
[arrAll, allUsers] = await Promise.all([
|
||||||
|
getCohorte(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
const tiposFiltro = COH_TIPOS[cohTipos].tipos;
|
||||||
|
const arrTipo = tiposFiltro ? arrAll.filter((o) => tiposFiltro.includes(o.tipo)) : arrAll;
|
||||||
|
const arr = applyFilt(arrTipo, filt);
|
||||||
|
|
||||||
|
const linkFor = (t) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (owner) params.set("owner", owner);
|
||||||
|
params.set("tipos", t);
|
||||||
|
return `/nuevas?${params.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const meses = [...new Set(arr.map((o) => o.mesCohorte).filter(Boolean))].sort();
|
||||||
|
const g = arr.filter((o) => o.estado === "Ganada");
|
||||||
|
const p = arr.filter((o) => o.estado === "Perdida");
|
||||||
|
const ab = arr.filter((o) => o.estado === "Abierta");
|
||||||
|
const cerr = g.length + p.length;
|
||||||
|
const pct = (x) => (arr.length ? Math.round((x / arr.length) * 100) : 0);
|
||||||
|
const mrrG = g.reduce((a, o) => a + o.val, 0);
|
||||||
|
|
||||||
|
const cohAgg = (key) => agg(arr, key, (o) => (o.estado === "Ganada" ? o.val : 0));
|
||||||
|
|
||||||
|
const cerradas = arr.filter((o) => o.diasACierre != null);
|
||||||
|
const tramos = [
|
||||||
|
{ lbl: "Mismo día", max: 0 }, { lbl: "1 a 7 días", max: 7 }, { lbl: "8 a 30 días", max: 30 },
|
||||||
|
{ lbl: "31 a 90 días", max: 90 }, { lbl: "Más de 90 días", max: Infinity },
|
||||||
|
];
|
||||||
|
let prev = -1;
|
||||||
|
const latRows = tramos.map((t) => {
|
||||||
|
const n = cerradas.filter((o) => o.diasACierre > prev && o.diasACierre <= t.max).length;
|
||||||
|
prev = t.max;
|
||||||
|
return { k: t.lbl, n };
|
||||||
|
});
|
||||||
|
const maxLat = Math.max(...latRows.map((r) => r.n), 1);
|
||||||
|
const medianaDias = (() => {
|
||||||
|
const a = cerradas.map((o) => o.diasACierre).sort((x, y) => x - y);
|
||||||
|
return a.length ? a[Math.floor(a.length / 2)] : 0;
|
||||||
|
})();
|
||||||
|
const viejas = arr.filter((o) => o.diasAbierta != null && o.diasAbierta > 90);
|
||||||
|
|
||||||
|
const detalle = [...arr].sort((a, b) => (b.estado === "Ganada" ? b.val : b.est) - (a.estado === "Ganada" ? a.val : a.est)).slice(0, 300);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Nuevas Oportunidades</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||||
|
{Object.entries(COH_TIPOS).map(([k, v]) => (
|
||||||
|
<a key={k} href={linkFor(k)}>
|
||||||
|
<button className={cohTipos === k ? "on" : ""} type="button">{v.lbl}</button>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{arr.length === 0 ? (
|
||||||
|
<p>No hay oportunidades creadas en el período y alcance seleccionados.</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{arr.length}</span><span className="l">Oportunidades creadas (cohorte)</span></div>
|
||||||
|
<div className="kpi"><span className="n" style={{ color: "var(--gana)" }}>{g.length}</span><span className="l">Hoy Ganadas · {pct(g.length)}%</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{p.length}</span><span className="l">Hoy Perdidas · {pct(p.length)}%</span></div>
|
||||||
|
<div className="kpi"><span className="n">{ab.length}</span><span className="l">Todavía Abiertas · {pct(ab.length)}%</span></div>
|
||||||
|
<div className="kpi"><span className="n">{cerr ? `${Math.round((g.length / cerr) * 100)}%` : "n/d"}</span><span className="l">Efectividad (gana ÷ resueltas)</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money(mrrG)}</span><span className="l">MRR ganado por esta cohorte</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="callout info">
|
||||||
|
<b>Esta página sigue a la misma población de principio a fin</b> — a diferencia del resto del informe,
|
||||||
|
que recorta por fecha de cierre y mezcla "lo que nació" con "lo que murió" ese mes. De las{" "}
|
||||||
|
<b>{arr.length}</b> oportunidades creadas en los últimos 6 meses, hoy {g.length} están ganadas, {p.length}{" "}
|
||||||
|
perdidas y {ab.length} siguen abiertas. Las cohortes recientes tienen más abiertas solo porque son
|
||||||
|
jóvenes — mirá "% resuelto" y la latencia antes de comparar. Plan de Cuenta y los leads de
|
||||||
|
formularios/bots convierten poco <b>por diseño</b> (los genera telemarketing en volumen); el error a
|
||||||
|
buscar ahí es lentitud para calificar, no baja conversión.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Desenlace por cohorte de creación (estado de hoy)</h3>
|
||||||
|
<p className="hint">Cada barra es el 100% de lo creado ese mes</p>
|
||||||
|
{meses.map((m) => <BarraCohorte key={m} mes={m} rows={arr.filter((o) => o.mesCohorte === m)} />)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ marginTop: 18 }}>
|
||||||
|
<CohMatriz arr={arr} meses={meses} dims={COH_DIMS} metricas={COH_METRICAS} activeDimKey={cohd} activeMetKey={cohm} mesLbl={mesLbl} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid2" style={{ marginTop: 18 }}>
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Latencia de decisión</h3>
|
||||||
|
<p className="hint">
|
||||||
|
De las {cerradas.length} ya resueltas: días entre crearlas y cerrarlas · normaliza el sesgo de madurez
|
||||||
|
</p>
|
||||||
|
{latRows.map((r) => (
|
||||||
|
<div className="row static" key={r.k}>
|
||||||
|
<div className="bl"><span className="nm">{r.k}</span></div>
|
||||||
|
<div className="bar-cell"><div className="bar-fill" style={{ width: `${(r.n / maxLat) * 100}%` }} /></div>
|
||||||
|
<span className="v">{r.n}</span>
|
||||||
|
<span className="c">{cerradas.length ? Math.round((r.n / cerradas.length) * 100) : 0}%</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<p className="hint" style={{ marginTop: 10 }}>
|
||||||
|
Mediana: <b>{medianaDias} días</b> para resolver.
|
||||||
|
{viejas.length > 0 && (
|
||||||
|
<> Y hay <b>{viejas.length}</b> todavía abiertas con más de 90 días de vida ({money(viejas.reduce((a, o) => a + o.est, 0))} estimado).</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Panel title="Por Origen de la Oportunidad" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("origen")} top={8} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid2" style={{ marginTop: 18 }}>
|
||||||
|
<Panel title="Por Tipo de Oportunidad" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("tipo")} />
|
||||||
|
<Panel title="Por Ejecutivo" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("owner")} />
|
||||||
|
</div>
|
||||||
|
<div className="grid2" style={{ marginTop: 18 }}>
|
||||||
|
<Panel title="Por Línea de Negocio" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("linea")} />
|
||||||
|
<Panel title="Por Campaña de Origen" hint="Barra = creadas · monto = MRR ya ganado" rows={cohAgg("campaign")} top={7} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="tw fit" style={{ marginTop: 18 }}>
|
||||||
|
<div className="tw-title">
|
||||||
|
<h3>Cohortes en números</h3>
|
||||||
|
<span className="tw-count">"% resuelto" y "edad promedio" dicen qué tan madura está cada cohorte</span>
|
||||||
|
</div>
|
||||||
|
<div className="ts" style={{ maxHeight: "none" }}>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cohorte</th><th className="num">Creadas</th><th className="num">Ganadas</th><th className="num">% Gana</th>
|
||||||
|
<th className="num">Perdidas</th><th className="num">% Pierde</th><th className="num">Abiertas</th>
|
||||||
|
<th className="num">% Resuelto</th><th className="num">MRR ganado</th><th className="num">Edad prom.</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{meses.map((m) => {
|
||||||
|
const c = arr.filter((o) => o.mesCohorte === m);
|
||||||
|
const cg = c.filter((o) => o.estado === "Ganada"), cp = c.filter((o) => o.estado === "Perdida"), ca = c.filter((o) => o.estado === "Abierta");
|
||||||
|
const cpct = (x) => (c.length ? `${Math.round((x / c.length) * 100)}%` : "—");
|
||||||
|
const cerrC = cg.length + cp.length;
|
||||||
|
const edad = c.length ? Math.round(c.reduce((s, o) => s + (o.diasACierre ?? o.diasAbierta ?? 0), 0) / c.length) : 0;
|
||||||
|
return (
|
||||||
|
<tr key={m}>
|
||||||
|
<td><b>{mesLbl(m)}</b></td>
|
||||||
|
<td className="num">{c.length}</td>
|
||||||
|
<td className="num" style={{ color: "var(--gana)", fontWeight: 700 }}>{cg.length}</td>
|
||||||
|
<td className="num">{cpct(cg.length)}</td>
|
||||||
|
<td className="num" style={{ color: "var(--pierde)", fontWeight: 700 }}>{cp.length}</td>
|
||||||
|
<td className="num">{cpct(cp.length)}</td>
|
||||||
|
<td className="num">{ca.length}</td>
|
||||||
|
<td className="num">{c.length ? `${Math.round((cerrC / c.length) * 100)}%` : "—"}</td>
|
||||||
|
<td className="num">{money(cg.reduce((s, o) => s + o.val, 0))}</td>
|
||||||
|
<td className="num">{edad} d</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ paddingBottom: 6, marginTop: 18 }}>
|
||||||
|
<h3>Detalle de la cohorte</h3>
|
||||||
|
<p className="hint">Las 300 de mayor monto · clic en el nombre abre Dynamics</p>
|
||||||
|
</div>
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente / Oportunidad</th><th>Estado</th><th>Ejecutivo</th><th>Tipo</th><th>Origen</th>
|
||||||
|
<th className="num">MRR</th><th>Creada</th><th className="num">Días</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{detalle.map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td className="dual-cel">
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener" title={o.name}>{o.name}</a>
|
||||||
|
<span className="sub">{o.cliente || "—"}</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={o.estado === "Ganada" ? "gana" : o.estado === "Perdida" ? "pierde" : ""}>{o.estado}</span>
|
||||||
|
</td>
|
||||||
|
<td className="elip">{o.owner}</td>
|
||||||
|
<td className="elip" title={o.tipo || ""}>{o.tipo || "—"}</td>
|
||||||
|
<td className="elip" title={o.origen || ""}>{o.origen || "—"}</td>
|
||||||
|
<td className="num">{money2(o.estado === "Ganada" ? o.val : o.est)}</td>
|
||||||
|
<td>{o.creada || "—"}</td>
|
||||||
|
<td className="num" title={o.diasACierre != null ? "Días que tardó en cerrarse" : "Días que lleva abierta"}>
|
||||||
|
{o.diasACierre != null ? o.diasACierre : o.diasAbierta != null ? `${o.diasAbierta}…` : "—"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
39
app/page.js
Normal file
39
app/page.js
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { auth } from "./lib/auth";
|
||||||
|
import { ownerFilter } from "./lib/authz";
|
||||||
|
import { getActividades, getSystemUsers } from "./lib/queries";
|
||||||
|
import { EJECUTIVOS_VENTA } from "./lib/derive";
|
||||||
|
import LoginPrompt from "./components/LoginPrompt";
|
||||||
|
import OwnerControl from "./components/OwnerControl";
|
||||||
|
import ErrorNotice from "./components/ErrorNotice";
|
||||||
|
import AgendaClient from "./components/agenda/AgendaClient";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function Home({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
|
||||||
|
let actividades, allUsers;
|
||||||
|
try {
|
||||||
|
[actividades, allUsers] = await Promise.all([
|
||||||
|
getActividades(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Agenda</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
<AgendaClient actividades={actividades} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/perdemos/loading.js
Normal file
4
app/perdemos/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
156
app/perdemos/page.js
Normal file
156
app/perdemos/page.js
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getClosed, getMotivosCierre, getSystemUsers } from "../lib/queries";
|
||||||
|
import { agg, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import Panel from "../components/pipeline/Panel";
|
||||||
|
import FilterChips from "../components/FilterChips";
|
||||||
|
import { DYN, money, money2 } from "../lib/constants";
|
||||||
|
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const DIM_LABELS = { motivo: "Motivo", competidor: "Competidor", servicio: "Servicio", origen: "Origen", owner: "Ejecutivo" };
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function PerdemosPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const mes = currentMonth();
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
|
||||||
|
let lostAll, allUsers;
|
||||||
|
try {
|
||||||
|
[lostAll, allUsers] = await Promise.all([
|
||||||
|
getClosed(session.accessToken, scope, 2, mes),
|
||||||
|
getSystemUsers(session.accessToken),
|
||||||
|
]);
|
||||||
|
const motivos = await getMotivosCierre(lostAll.map((o) => o.id), session.accessToken);
|
||||||
|
lostAll = lostAll.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor }));
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
const lost = applyFilt(lostAll, filt);
|
||||||
|
|
||||||
|
const mrrPerdido = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||||
|
const clientesNuevos = lost.filter((o) => o.segmento === "Clientes Nuevos").length;
|
||||||
|
const carteraActiva = lost.filter((o) => o.segmento === "Cartera Activa").length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Por qué Perdemos — {mes}</h2>
|
||||||
|
<OwnerControl
|
||||||
|
owners={owners}
|
||||||
|
current={scope.locked ? session.email : scope.email}
|
||||||
|
locked={scope.locked}
|
||||||
|
lockedLabel={session.email}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{lost.length}</span>
|
||||||
|
<span className="l">Oportunidades perdidas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{money(mrrPerdido)}</span>
|
||||||
|
<span className="l">MRR estimado perdido</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{clientesNuevos}</span>
|
||||||
|
<span className="l">Clientes Nuevos</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{carteraActiva}</span>
|
||||||
|
<span className="l">Cartera Activa</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="hint">
|
||||||
|
No hay seguimiento registrado en el CRM ≠ no hubo seguimiento — la mayoría del contacto comercial se hace por
|
||||||
|
WhatsApp, que no está integrado a Dynamics (ver CLAUDE.md).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
<div className="grid2">
|
||||||
|
<Panel
|
||||||
|
title="Motivo de cierre"
|
||||||
|
hint='Fuente: Cierre de oportunidad en Dynamics · "Sin registrar" = ningún motivo (Alfa ni estándar) quedó guardado'
|
||||||
|
rows={agg(lost, "motivo", (o) => o.est)}
|
||||||
|
cls="pierde"
|
||||||
|
dimKey="motivo"
|
||||||
|
/>
|
||||||
|
<Panel
|
||||||
|
title="Competidor"
|
||||||
|
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Ninguno"), "competidor", (o) => o.est)}
|
||||||
|
cls="pierde"
|
||||||
|
dimKey="competidor"
|
||||||
|
/>
|
||||||
|
<Panel title="Servicio / Producto" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" dimKey="servicio" />
|
||||||
|
<Panel title="Origen de la oportunidad" rows={agg(lost, "origen", (o) => o.est)} cls="pierde" dimKey="origen" />
|
||||||
|
<Panel title="Perdidas por ejecutivo" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" dimKey="owner" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de oportunidades perdidas</h3>
|
||||||
|
<p className="hint">Clic en el nombre abre la oportunidad en Dynamics 365</p>
|
||||||
|
</div>
|
||||||
|
{lost.length === 0 ? (
|
||||||
|
<p>No hay oportunidades perdidas en este período para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Seg.</th>
|
||||||
|
<th>Motivo de cierre</th>
|
||||||
|
<th>Línea de Negocio</th>
|
||||||
|
<th>Competidor</th>
|
||||||
|
{!scope.locked && <th>Ejecutivo</th>}
|
||||||
|
<th className="num">MRR est.</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td>{o.cliente || "—"}</td>
|
||||||
|
<td>
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||||
|
{o.name}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`pill ${o.segmento === "Cartera Activa" ? "cartera" : "nuevo"}`}>
|
||||||
|
{o.segmento === "Cartera Activa" ? "CA" : "CN"}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>{o.motivo}</td>
|
||||||
|
<td>{o.linea || "—"}</td>
|
||||||
|
<td>{o.competidor || "—"}</td>
|
||||||
|
{!scope.locked && <td>{o.owner}</td>}
|
||||||
|
<td className="num">{o.est ? money2(o.est) : "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/prevision/loading.js
Normal file
4
app/prevision/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
294
app/prevision/page.js
Normal file
294
app/prevision/page.js
Normal file
|
|
@ -0,0 +1,294 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getPipeline, getSystemUsers, getActividades } from "../lib/queries";
|
||||||
|
import { agg, aggOrd, EJECUTIVOS_VENTA, hayClasif, decorarActividadVentana, ACTAGENDADA_ORDEN } from "../lib/derive";
|
||||||
|
import { getMetaGlobal } from "../lib/metas";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import Panel from "../components/pipeline/Panel";
|
||||||
|
import MatrizCalidad from "../components/pipeline/MatrizCalidad";
|
||||||
|
import TablaPipe from "../components/pipeline/TablaPipe";
|
||||||
|
import ExecMatrix from "../components/pipeline/ExecMatrix";
|
||||||
|
import SegTabs from "../components/SegTabs";
|
||||||
|
import FilterChips from "../components/FilterChips";
|
||||||
|
import { DYN, money, money2 } from "../lib/constants";
|
||||||
|
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const IND_TABS = [
|
||||||
|
{ k: "owner", lbl: "Ejecutivo" },
|
||||||
|
{ k: "tipo", lbl: "Tipo" },
|
||||||
|
{ k: "origen", lbl: "Origen" },
|
||||||
|
];
|
||||||
|
const IND_TITULOS = {
|
||||||
|
owner: "Por Ejecutivo",
|
||||||
|
tipo: "Por Tipo de Oportunidad",
|
||||||
|
origen: "Por Origen de Oportunidad",
|
||||||
|
};
|
||||||
|
const IND_TOP = { owner: undefined, tipo: undefined, origen: 7 };
|
||||||
|
const DIM_LABELS = { owner: "Ejecutivo", tipo: "Tipo", origen: "Origen", luz: "Luz Amarilla", plan: "Plan de Cierre", calidad: "Calidad", mov: "Movimiento", actAgendada: "Agendado" };
|
||||||
|
|
||||||
|
const PREVIS_TIPOS = ["Venta - Cliente Nuevo", "Up-Selling", "Cross-Selling"];
|
||||||
|
const PREVIS_PLANES_EXCL = ["Sin plan de cierre", "Plan D - Recalificar"];
|
||||||
|
const ATRASADAS = "__ATRASADAS__";
|
||||||
|
|
||||||
|
const BLOCKER_INFO = {
|
||||||
|
precio: { label: "Precio / oferta no competitiva", accion: "Evaluar un acelerador puntual: descuento, mes de cortesía o ajuste de instalación." },
|
||||||
|
aprobacion: { label: "Esperando aprobación interna del cliente", accion: "Escalar con una llamada ejecutivo a gerente para destrabar la firma." },
|
||||||
|
licitacion: { label: "Proceso de licitación externo", accion: "Fuera de control directo por ahora — mantener la relación." },
|
||||||
|
};
|
||||||
|
|
||||||
|
function classifyBlocker(txt) {
|
||||||
|
txt = (txt || "").toLowerCase();
|
||||||
|
if (/licitaci|licitatorio/.test(txt)) return "licitacion";
|
||||||
|
if (/precio|tarifa|descuento|presupuesto|\bcost[oa]\b|\bcara\b|instalaci[oó]n/.test(txt)) return "precio";
|
||||||
|
if (/aprobaci|aprobar|aprob[oó]|gerencia|gerente|\bfirma\b|firmar|comit[eé]/.test(txt)) return "aprobacion";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ventana de fechas del mes 'YYYY-MM' seleccionado, para cruzar con Actividades — puerto de
|
||||||
|
// ventanaDeMes() (App Informe/assets/js/utils.js). Atrasadas no tiene fin natural (ya venció): se
|
||||||
|
// lee como "¿ya se agendó algo desde hoy en adelante para corregirla?".
|
||||||
|
function ventanaDeMes(win, hoyIso) {
|
||||||
|
if (win === ATRASADAS) return { ini: hoyIso, fin: "9999-12-31" };
|
||||||
|
const [y, m] = win.split("-").map(Number);
|
||||||
|
const fin = new Date(y, m, 0);
|
||||||
|
return { ini: `${win}-01`, fin: `${fin.getFullYear()}-${String(fin.getMonth() + 1).padStart(2, "0")}-${String(fin.getDate()).padStart(2, "0")}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function PrevisionPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner, w: winParam } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const hoy = currentMonth();
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||||
|
const mze = sp.mze;
|
||||||
|
|
||||||
|
let allRows, allUsers, actividades;
|
||||||
|
try {
|
||||||
|
[allRows, allUsers, actividades] = await Promise.all([
|
||||||
|
getPipeline(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
getActividades(session.accessToken, scope),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
|
||||||
|
const base = allRows.filter((o) => PREVIS_TIPOS.includes(o.tipo) && !PREVIS_PLANES_EXCL.includes(o.plan));
|
||||||
|
const futuros = [...new Set(base.map((o) => o.mesCierre).filter((m) => m && m >= hoy))].sort();
|
||||||
|
const atrasadas = base.filter((o) => !o.mesCierre || o.mesCierre < hoy);
|
||||||
|
const win = winParam === ATRASADAS ? ATRASADAS : futuros.includes(winParam) ? winParam : futuros[0] || hoy;
|
||||||
|
const hoyIso = new Date().toISOString().slice(0, 10);
|
||||||
|
const { ini, fin } = ventanaDeMes(win, hoyIso);
|
||||||
|
const pWinRaw = win === ATRASADAS ? atrasadas : base.filter((o) => o.mesCierre === win);
|
||||||
|
const pWin = decorarActividadVentana(pWinRaw, actividades, ini, fin);
|
||||||
|
const p = applyFilt(pWin, filt);
|
||||||
|
|
||||||
|
const est = p.reduce((a, o) => a + o.est, 0);
|
||||||
|
const fc = p.reduce((a, o) => a + o.fc, 0);
|
||||||
|
const estanc = p.filter((o) => o.estanc);
|
||||||
|
const metaGlobal = getMetaGlobal();
|
||||||
|
const coverage = metaGlobal ? Math.round((fc / metaGlobal) * 100) : null;
|
||||||
|
|
||||||
|
const groups = { precio: [], aprobacion: [], licitacion: [] };
|
||||||
|
p.forEach((o) => {
|
||||||
|
const cat = classifyBlocker(o.estado);
|
||||||
|
if (cat) groups[cat].push(o);
|
||||||
|
});
|
||||||
|
|
||||||
|
const accionablesBlock = (
|
||||||
|
<>
|
||||||
|
{Object.entries(groups).some(([, v]) => v.length > 0) && (
|
||||||
|
<div className="panel" style={{ marginTop: 18 }}>
|
||||||
|
<h3>Oportunidades para accionar esta semana</h3>
|
||||||
|
<p className="hint">Clasificado por palabras clave en "Estado de la Negociación" de Dynamics.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{Object.entries(groups)
|
||||||
|
.filter(([, list]) => list.length > 0)
|
||||||
|
.map(([key, list]) => {
|
||||||
|
const gEst = list.reduce((a, o) => a + o.est, 0);
|
||||||
|
const gFc = list.reduce((a, o) => a + o.fc, 0);
|
||||||
|
return (
|
||||||
|
<div className="panel" style={{ marginBottom: 14 }} key={key}>
|
||||||
|
<h3>
|
||||||
|
{BLOCKER_INFO[key].label} — {list.length} oport. · {money(gEst)} est. · {money(gFc)} ponderado
|
||||||
|
</h3>
|
||||||
|
<p className="hint">{BLOCKER_INFO[key].accion}</p>
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Ejecutivo</th>
|
||||||
|
<th className="num">MRR</th>
|
||||||
|
<th>Nota de negociación</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{[...list].sort((a, b) => b.est - a.est).map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td>{o.cliente || "—"}</td>
|
||||||
|
<td>
|
||||||
|
<a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">
|
||||||
|
{o.name}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>{o.owner}</td>
|
||||||
|
<td className="num">{money2(o.est)}</td>
|
||||||
|
<td style={{ color: "var(--tinta-suave)", fontSize: 12 }}>
|
||||||
|
{(o.estado || "").slice(0, 100)}
|
||||||
|
{(o.estado || "").length > 100 ? "…" : ""}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const linkFor = (w) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (owner) params.set("owner", owner);
|
||||||
|
params.set("w", w);
|
||||||
|
return `/prevision?${params.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Previsión de Ventas</h2>
|
||||||
|
<OwnerControl
|
||||||
|
owners={owners}
|
||||||
|
current={scope.locked ? session.email : scope.email}
|
||||||
|
locked={scope.locked}
|
||||||
|
lockedLabel={session.email}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="hint" style={{ marginBottom: 8 }}>
|
||||||
|
Solo considera oportunidades con Plan de Cierre A, B o C (se excluyen "Sin plan de cierre" y "Plan D -
|
||||||
|
Recalificar" por no tener compromiso de cierre real).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||||
|
{atrasadas.length > 0 && (
|
||||||
|
<a href={linkFor(ATRASADAS)}>
|
||||||
|
<button className={win === ATRASADAS ? "on" : ""} type="button">
|
||||||
|
⚠ Atrasadas ({atrasadas.length})
|
||||||
|
</button>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{futuros.map((m) => (
|
||||||
|
<a key={m} href={linkFor(m)}>
|
||||||
|
<button className={win === m ? "on" : ""} type="button">
|
||||||
|
{m}
|
||||||
|
</button>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{p.length}</span>
|
||||||
|
<span className="l">Oportunidades en esta ventana</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money(est)}</span>
|
||||||
|
<span className="l">Valor estimado (MRR)</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money(fc)}</span>
|
||||||
|
<span className="l">Forecast ponderado</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={coverage != null && coverage < 100 ? "n pierde" : "n"}>
|
||||||
|
{coverage != null ? `${coverage}%` : "n/d"}
|
||||||
|
</span>
|
||||||
|
<span className="l">Coverage vs meta equipo ({money(metaGlobal)})</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{estanc.length}</span>
|
||||||
|
<span className="l">En riesgo (estancadas)</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>Forecast ponderado = Σ (MRR estimado × probabilidad del Plan de Cierre).</b> Pesos: Plan A 90% · Plan B
|
||||||
|
60% · Plan C 30%. Este número no castiga la antigüedad — una oferta de hace 5 días pesa igual que una de 144
|
||||||
|
días. Cruzar siempre con "Días en fase" antes de darlo por seguro.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{p.length > 0 && <ExecMatrix arr={p} titulo="Forecast por ejecutivo" valor={(o) => o.fc} hint="Forecast ponderado (MRR × peso del plan) por ejecutivo y Plan de Cierre" activeDim={mze} />}
|
||||||
|
|
||||||
|
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
{pWin.length === 0 ? (
|
||||||
|
<p>No hay oportunidades en esta ventana.</p>
|
||||||
|
) : (
|
||||||
|
<div className="split23">
|
||||||
|
<div className="split23-ind">
|
||||||
|
{hayClasif(p) && <MatrizCalidad arr={p} />}
|
||||||
|
<Panel
|
||||||
|
title="Luz Amarilla — qué la detiene"
|
||||||
|
hint="Bloqueador declarado por el ejecutivo"
|
||||||
|
rows={agg(p, "luz", (o) => o.fc)}
|
||||||
|
cls="alerta"
|
||||||
|
top={7}
|
||||||
|
byVal
|
||||||
|
dimKey="luz"
|
||||||
|
/>
|
||||||
|
<Panel
|
||||||
|
title="¿Ya se agendó algo?"
|
||||||
|
hint={`Tarea/Cita/Llamada dentro de la ventana seleccionada`}
|
||||||
|
rows={aggOrd(p, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.fc)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="actAgendada"
|
||||||
|
/>
|
||||||
|
<Panel title="Forecast por Plan de Cierre" rows={agg(p, "plan", (o) => o.fc)} byVal dimKey="plan" />
|
||||||
|
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||||
|
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title={IND_TITULOS[indActive]}
|
||||||
|
hint="Ordenado por forecast ponderado"
|
||||||
|
rows={agg(p, indActive, (o) => o.fc)}
|
||||||
|
top={IND_TOP[indActive]}
|
||||||
|
byVal
|
||||||
|
dimKey={indActive}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Oportunidades con cierre estimado en esta ventana</h3>
|
||||||
|
<p className="hint">Forecast = MRR × peso del plan · scroll horizontal con la columna fija · clic en el nombre abre Dynamics</p>
|
||||||
|
</div>
|
||||||
|
<TablaPipe arr={p} tipo="fc" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{accionablesBlock}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/renovaciones/logradas/loading.js
Normal file
4
app/renovaciones/logradas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
139
app/renovaciones/logradas/page.js
Normal file
139
app/renovaciones/logradas/page.js
Normal file
|
|
@ -0,0 +1,139 @@
|
||||||
|
import { auth } from "../../lib/auth";
|
||||||
|
import { ownerFilter } from "../../lib/authz";
|
||||||
|
import { getRenovClosed, getSystemUsers } from "../../lib/queries";
|
||||||
|
import { agg, EJECUTIVOS_RENOV } from "../../lib/derive";
|
||||||
|
import LoginPrompt from "../../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../../components/ErrorNotice";
|
||||||
|
import Panel from "../../components/pipeline/Panel";
|
||||||
|
import WonTable from "../../components/pipeline/WonTable";
|
||||||
|
import { money, money2 } from "../../lib/constants";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function retencion(w, l) {
|
||||||
|
const t = w.length + l.length;
|
||||||
|
return t ? Math.round((w.length / t) * 100) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function RenovLogradasPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const mes = currentMonth();
|
||||||
|
|
||||||
|
let wonRaw, lost, allUsers;
|
||||||
|
try {
|
||||||
|
[wonRaw, lost, allUsers] = await Promise.all([
|
||||||
|
getRenovClosed(session.accessToken, scope, 1, mes),
|
||||||
|
getRenovClosed(session.accessToken, scope, 2, mes),
|
||||||
|
getSystemUsers(session.accessToken),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||||
|
const won = wonRaw.map((o) => ({ ...o, val: o.actual }));
|
||||||
|
|
||||||
|
const sumW = won.reduce((a, o) => a + o.val, 0);
|
||||||
|
const sumL = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||||
|
const ret = retencion(won, lost);
|
||||||
|
const aTiempo = won.filter((o) => o.tipo === "Próximo a Vencer en 30/60/90").length;
|
||||||
|
const pctATiempo = won.length ? Math.round((aTiempo / won.length) * 100) : 0;
|
||||||
|
|
||||||
|
// Retención por ejecutivo — ganadas vs. perdidas de cada quien, en MRR.
|
||||||
|
const ejecutivos = [...new Set([...won.map((o) => o.owner), ...lost.map((o) => o.owner)])];
|
||||||
|
const retPorEjec = ejecutivos
|
||||||
|
.map((ow) => ({
|
||||||
|
k: ow,
|
||||||
|
gana: won.filter((o) => o.owner === ow).reduce((a, o) => a + o.val, 0),
|
||||||
|
pierde: lost.filter((o) => o.owner === ow).reduce((a, o) => a + (o.est || 0), 0),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => b.gana + b.pierde - (a.gana + a.pierde));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Renovaciones Logradas — {mes}</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{money2(sumW)}</span><span className="l">MRR renovado</span></div>
|
||||||
|
<div className="kpi"><span className="n">{won.length}</span><span className="l">Renovaciones logradas</span></div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={`n ${ret != null && ret < 80 ? "pierde" : ""}`}>{ret == null ? "n/d" : `${ret}%`}</span>
|
||||||
|
<span className="l">Tasa de retención (ganadas ÷ cerradas)</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi"><span className="n pierde">{money2(sumL)}</span><span className="l">MRR perdido por no renovar</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money2(won.length ? sumW / won.length : 0)}</span><span className="l">Ticket promedio renovado</span></div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={`n ${pctATiempo < 50 ? "pierde" : ""}`}>{pctATiempo}%</span>
|
||||||
|
<span className="l">Renovadas ANTES de vencer</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={`callout ${ret != null && ret < 80 ? "warn" : "info"}`}>
|
||||||
|
<b>De cada 100 contratos que se cerraron este mes, se conservaron {ret == null ? "—" : ret}.</b> Acá no hay
|
||||||
|
meta que cumplir: la meta comercial excluye renovaciones a propósito, porque mide negocio nuevo y de
|
||||||
|
expansión. Eso no las hace menores. El número que sí manda acá es la retención, y el costo de fallar es
|
||||||
|
churn.
|
||||||
|
</div>
|
||||||
|
{pctATiempo < 50 && (
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>Solo {pctATiempo}% se renovó antes de vencer</b> ({aTiempo} de {won.length}). Las otras se firmaron con
|
||||||
|
el contrato ya vencido — funciona, pero es la ventana donde el cliente está más expuesto a que lo llame la
|
||||||
|
competencia. Adelantar la gestión al tipo «Próximo a Vencer 30/60/90» es la palanca directa sobre este
|
||||||
|
número.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{retPorEjec.length > 0 && (
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Retención por ejecutivo</h3>
|
||||||
|
<p className="hint">Ganadas vs. perdidas de cada quien, en MRR</p>
|
||||||
|
{retPorEjec.map((r) => {
|
||||||
|
const max = Math.max(...retPorEjec.flatMap((x) => [x.gana, x.pierde]), 0.1);
|
||||||
|
return (
|
||||||
|
<div key={r.k} style={{ padding: "7px 4px", borderBottom: "1px solid var(--linea)" }}>
|
||||||
|
<div style={{ fontSize: 12.5, marginBottom: 5 }}>{r.k}</div>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
|
||||||
|
<span style={{ fontSize: 10, color: "var(--gana)", width: 52 }}>Gana</span>
|
||||||
|
<div className="bar-cell"><div className="bar-fill" style={{ width: `${(r.gana / max) * 100}%` }} /></div>
|
||||||
|
<span className="v">{money2(r.gana)}</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||||
|
<span style={{ fontSize: 10, color: "var(--pierde)", width: 52 }}>Pierde</span>
|
||||||
|
<div className="bar-cell"><div className="bar-fill pierde" style={{ width: `${(r.pierde / max) * 100}%` }} /></div>
|
||||||
|
<span className="v">{money2(r.pierde)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid3">
|
||||||
|
<Panel title="Por momento de la renovación" hint="A tiempo vs. tarde" rows={agg(won, "tipo", (o) => o.val)} />
|
||||||
|
<Panel title="Por Ejecutivo" hint="Ordenado por MRR renovado" rows={agg(won, "owner", (o) => o.val)} />
|
||||||
|
<Panel title="Por Línea de Negocio" hint="Ordenado por MRR renovado" rows={agg(won, "linea", (o) => o.val)} />
|
||||||
|
<Panel title="Por Servicio / Producto" hint="Ordenado por MRR renovado" rows={agg(won, "servicio", (o) => o.val)} top={7} />
|
||||||
|
<Panel title="Por Origen" hint="Canal registrado de la oportunidad" rows={agg(won, "origen", (o) => o.val)} top={7} />
|
||||||
|
<Panel title="Por Cliente" hint="Las cuentas que más MRR renovaron" rows={agg(won, "cliente", (o) => o.val)} top={7} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de renovaciones logradas</h3>
|
||||||
|
<p className="hint">Clic en el nombre abre la oportunidad en Dynamics 365</p>
|
||||||
|
</div>
|
||||||
|
{won.length === 0 ? <p>No hay renovaciones logradas en este período para este filtro.</p> : <WonTable rows={won} locked={scope.locked} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/renovaciones/perdidas/loading.js
Normal file
4
app/renovaciones/perdidas/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
143
app/renovaciones/perdidas/page.js
Normal file
143
app/renovaciones/perdidas/page.js
Normal file
|
|
@ -0,0 +1,143 @@
|
||||||
|
import { auth } from "../../lib/auth";
|
||||||
|
import { ownerFilter } from "../../lib/authz";
|
||||||
|
import { getRenovClosed, getMotivosCierre, getSystemUsers } from "../../lib/queries";
|
||||||
|
import { agg, EJECUTIVOS_RENOV, catsWonLost } from "../../lib/derive";
|
||||||
|
import LoginPrompt from "../../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../../components/ErrorNotice";
|
||||||
|
import Panel from "../../components/pipeline/Panel";
|
||||||
|
import ComparePanelMotivo from "../../components/pipeline/ComparePanelMotivo";
|
||||||
|
import { DYN, money2 } from "../../lib/constants";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function retencion(w, l) {
|
||||||
|
const t = w.length + l.length;
|
||||||
|
return t ? Math.round((w.length / t) * 100) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function RenovPerdidasPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const mes = currentMonth();
|
||||||
|
|
||||||
|
let lost, won, allUsers;
|
||||||
|
try {
|
||||||
|
[lost, won, allUsers] = await Promise.all([
|
||||||
|
getRenovClosed(session.accessToken, scope, 2, mes),
|
||||||
|
getRenovClosed(session.accessToken, scope, 1, mes),
|
||||||
|
getSystemUsers(session.accessToken),
|
||||||
|
]);
|
||||||
|
const motivos = await getMotivosCierre(lost.map((o) => o.id), session.accessToken);
|
||||||
|
lost = lost.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar", competidor: motivos[o.id]?.competidor || o.competidor }));
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||||
|
|
||||||
|
const sumL = lost.reduce((a, o) => a + (o.est || 0), 0);
|
||||||
|
const ret = retencion(won, lost);
|
||||||
|
const churn = ret == null ? null : 100 - ret;
|
||||||
|
const depu = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||||
|
const conMotivo = lost.length - depu;
|
||||||
|
const catsLinea = catsWonLost(won, lost, "linea");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Renovaciones Perdidas — {mes}</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n pierde">{lost.length}</span><span className="l">Contratos no renovados</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{money2(sumL)}</span><span className="l">MRR perdido</span></div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={`n ${churn != null && churn > 20 ? "pierde" : ""}`}>{churn == null ? "n/d" : `${churn}%`}</span>
|
||||||
|
<span className="l">Churn del período</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi"><span className="n">{conMotivo}</span><span className="l">Con motivo real declarado</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money2(lost.length ? sumL / lost.length : 0)}</span><span className="l">Ticket promedio perdido</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>Cada contrato de esta lista es MRR que ya estaba adentro y se fue.</b>{" "}
|
||||||
|
{depu > 0 && (
|
||||||
|
<>Ojo con la lectura: <b>{depu} de {lost.length}</b> cerraron como Envejecida/Cancelada/Agotada, que es
|
||||||
|
depuración de registros y no un rechazo del cliente — el análisis de causa real se apoya en las{" "}
|
||||||
|
{conMotivo} restantes. </>
|
||||||
|
)}
|
||||||
|
Y recordá que <b>el seguimiento por WhatsApp no está integrado a Dynamics</b>: cuando el motivo queda vacío,
|
||||||
|
lo correcto es decir «no hay motivo registrado en el CRM», no «no se gestionó».
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{catsLinea.length > 0 && (
|
||||||
|
<ComparePanelMotivo
|
||||||
|
title="Renovación por línea de negocio: qué se conserva y qué se va"
|
||||||
|
hint="Ganadas vs. perdidas en MRR, por línea de negocio"
|
||||||
|
cats={catsLinea}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid3">
|
||||||
|
<Panel title="Motivo de cierre" hint="Fuente: Cierre de oportunidad en Dynamics" rows={agg(lost, "motivo", (o) => o.est)} cls="pierde" />
|
||||||
|
<Panel title="Por momento de la renovación" hint="¿Se perdió antes o después de vencer el contrato?" rows={agg(lost, "tipo", (o) => o.est)} cls="pierde" />
|
||||||
|
<Panel
|
||||||
|
title="Competidor"
|
||||||
|
hint="Contra quién se perdió"
|
||||||
|
rows={agg(lost.filter((o) => o.competidor && o.competidor !== "Sin registrar"), "competidor", (o) => o.est)}
|
||||||
|
cls="pierde"
|
||||||
|
top={7}
|
||||||
|
/>
|
||||||
|
<Panel title="Por Ejecutivo" hint="Ordenado por MRR perdido" rows={agg(lost, "owner", (o) => o.est)} cls="pierde" />
|
||||||
|
<Panel title="Por Línea de Negocio" hint="Ordenado por MRR perdido" rows={agg(lost, "linea", (o) => o.est)} cls="pierde" />
|
||||||
|
<Panel title="Por Servicio / Producto" hint="Ordenado por MRR perdido" rows={agg(lost, "servicio", (o) => o.est)} cls="pierde" top={7} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de contratos no renovados</h3>
|
||||||
|
<p className="hint">Clic en el nombre abre la oportunidad en Dynamics 365</p>
|
||||||
|
</div>
|
||||||
|
{lost.length === 0 ? (
|
||||||
|
<p>No hay renovaciones perdidas en este período para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<div className="tw">
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Cliente</th>
|
||||||
|
<th>Oportunidad</th>
|
||||||
|
<th>Motivo de cierre</th>
|
||||||
|
<th>Línea de Negocio</th>
|
||||||
|
{!scope.locked && <th>Ejecutivo</th>}
|
||||||
|
<th className="num">MRR est.</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{[...lost].sort((a, b) => (b.est || 0) - (a.est || 0)).map((o) => (
|
||||||
|
<tr key={o.id}>
|
||||||
|
<td>{o.cliente || "—"}</td>
|
||||||
|
<td><a className="opp" href={`${DYN}${o.id}`} target="_blank" rel="noopener">{o.name}</a></td>
|
||||||
|
<td>{o.motivo}</td>
|
||||||
|
<td>{o.linea || "—"}</td>
|
||||||
|
{!scope.locked && <td>{o.owner}</td>}
|
||||||
|
<td className="num">{o.est ? money2(o.est) : "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/renovaciones/prevision/loading.js
Normal file
4
app/renovaciones/prevision/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
222
app/renovaciones/prevision/page.js
Normal file
222
app/renovaciones/prevision/page.js
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
import { auth } from "../../lib/auth";
|
||||||
|
import { ownerFilter } from "../../lib/authz";
|
||||||
|
import { getRenovPipeline, getRenovClosed, getSystemUsers, getActividades } from "../../lib/queries";
|
||||||
|
import { agg, aggOrd, EJECUTIVOS_RENOV, decorarActividadVentana, ACTAGENDADA_ORDEN } from "../../lib/derive";
|
||||||
|
import LoginPrompt from "../../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../../components/ErrorNotice";
|
||||||
|
import Panel from "../../components/pipeline/Panel";
|
||||||
|
import TablaPipe from "../../components/pipeline/TablaPipe";
|
||||||
|
import ExecMatrix from "../../components/pipeline/ExecMatrix";
|
||||||
|
import SegTabs from "../../components/SegTabs";
|
||||||
|
import FilterChips from "../../components/FilterChips";
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const IND_TABS = [
|
||||||
|
{ k: "owner", lbl: "Ejecutivo" },
|
||||||
|
{ k: "cliente", lbl: "Cliente" },
|
||||||
|
{ k: "linea", lbl: "Línea" },
|
||||||
|
{ k: "competidor", lbl: "Competidor" },
|
||||||
|
];
|
||||||
|
const IND_TITULOS = {
|
||||||
|
owner: "Por Ejecutivo",
|
||||||
|
cliente: "Por Cliente",
|
||||||
|
linea: "Por Línea de Negocio",
|
||||||
|
competidor: "Por Competidor",
|
||||||
|
};
|
||||||
|
const IND_HINTS = {
|
||||||
|
owner: "Ordenado por MRR en juego",
|
||||||
|
cliente: "Las cuentas con más MRR por renovar este mes",
|
||||||
|
linea: "Ordenado por MRR en juego",
|
||||||
|
competidor: "Contra quién se compite la renovación",
|
||||||
|
};
|
||||||
|
const IND_TOP = { owner: undefined, cliente: 7, linea: undefined, competidor: 7 };
|
||||||
|
const DIM_LABELS = { owner: "Ejecutivo", cliente: "Cliente", linea: "Línea", competidor: "Competidor", tipo: "Momento", actAgendada: "Agendado" };
|
||||||
|
|
||||||
|
const ATRASADAS = "__ATRASADAS__";
|
||||||
|
const MESLBL_CAP = {
|
||||||
|
"01": "Enero", "02": "Febrero", "03": "Marzo", "04": "Abril", "05": "Mayo", "06": "Junio",
|
||||||
|
"07": "Julio", "08": "Agosto", "09": "Septiembre", "10": "Octubre", "11": "Noviembre", "12": "Diciembre",
|
||||||
|
};
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
function mesAnterior(m, n) {
|
||||||
|
const [y, mm] = m.split("-").map(Number);
|
||||||
|
const d = new Date(y, mm - 1 - n, 1);
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
function ventanaDeMes(win, hoyIso) {
|
||||||
|
if (win === ATRASADAS) return { ini: hoyIso, fin: "9999-12-31" };
|
||||||
|
const [y, m] = win.split("-").map(Number);
|
||||||
|
const fin = new Date(y, m, 0);
|
||||||
|
return { ini: `${win}-01`, fin: `${fin.getFullYear()}-${String(fin.getMonth() + 1).padStart(2, "0")}-${String(fin.getDate()).padStart(2, "0")}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function RenovPrevisionPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner, w: winParam } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const hoy = currentMonth();
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||||
|
const mze = sp.mze;
|
||||||
|
|
||||||
|
let allRows, allUsers, historico, actividades;
|
||||||
|
try {
|
||||||
|
[allRows, allUsers, actividades] = await Promise.all([
|
||||||
|
getRenovPipeline(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
getActividades(session.accessToken, scope, EJECUTIVOS_RENOV),
|
||||||
|
]);
|
||||||
|
// Referencia honesta: MRR realmente renovado en los 3 meses cerrados anteriores.
|
||||||
|
const meses3 = [mesAnterior(hoy, 1), mesAnterior(hoy, 2), mesAnterior(hoy, 3)];
|
||||||
|
const won3 = await Promise.all(meses3.map((m) => getRenovClosed(session.accessToken, scope, 1, m)));
|
||||||
|
historico = won3.map((w) => w.reduce((a, o) => a + (o.actual || 0), 0));
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||||
|
const histProm = historico.length ? historico.reduce((a, b) => a + b, 0) / historico.length : 0;
|
||||||
|
|
||||||
|
const futuros = [...new Set(allRows.map((o) => o.mesCierre).filter((m) => m && m >= hoy))].sort();
|
||||||
|
const atrasadas = allRows.filter((o) => !o.mesCierre || o.mesCierre < hoy);
|
||||||
|
const win = winParam === ATRASADAS ? ATRASADAS : futuros.includes(winParam) ? winParam : futuros[0] || hoy;
|
||||||
|
const hoyIso = new Date().toISOString().slice(0, 10);
|
||||||
|
const { ini, fin: finVentana } = ventanaDeMes(win, hoyIso);
|
||||||
|
const pWinRaw = win === ATRASADAS ? atrasadas : allRows.filter((o) => o.mesCierre === win);
|
||||||
|
const pWin = decorarActividadVentana(pWinRaw, actividades, ini, finVentana);
|
||||||
|
const p = applyFilt(pWin, filt);
|
||||||
|
const winLbl = win === ATRASADAS ? "renovaciones atrasadas (fecha estimada ya vencida)" : MESLBL_CAP[win.slice(5, 7)] || win;
|
||||||
|
|
||||||
|
const est = p.reduce((a, o) => a + o.est, 0);
|
||||||
|
const fc = p.reduce((a, o) => a + o.fc, 0);
|
||||||
|
const estanc = p.filter((o) => o.estanc);
|
||||||
|
const sinPlan = p.filter((o) => o.plan === "Sin plan de cierre");
|
||||||
|
const cob = histProm ? Math.round((fc / histProm) * 100) : null;
|
||||||
|
|
||||||
|
const porMes = futuros.map((m) => ({
|
||||||
|
lbl: MESLBL_CAP[m.slice(5, 7)] || m,
|
||||||
|
n: allRows.filter((o) => o.mesCierre === m).length,
|
||||||
|
est: allRows.filter((o) => o.mesCierre === m).reduce((a, o) => a + o.est, 0),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const linkFor = (w) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (owner) params.set("owner", owner);
|
||||||
|
params.set("w", w);
|
||||||
|
return `/renovaciones/prevision?${params.toString()}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Previsión de Renovaciones</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="seg-tabs" style={{ marginBottom: 16, flexWrap: "wrap" }}>
|
||||||
|
{atrasadas.length > 0 && (
|
||||||
|
<a href={linkFor(ATRASADAS)}>
|
||||||
|
<button className={win === ATRASADAS ? "on" : ""} type="button">⚠ Atrasadas ({atrasadas.length})</button>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
{futuros.map((m) => (
|
||||||
|
<a key={m} href={linkFor(m)}>
|
||||||
|
<button className={win === m ? "on" : ""} type="button">{MESLBL_CAP[m.slice(5, 7)] || m}</button>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{p.length}</span><span className="l">Renovaciones que vencen en {winLbl}</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money(est)}</span><span className="l">MRR en juego</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money(fc)}</span><span className="l">Forecast ponderado</span></div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={`n ${cob != null && cob < 100 ? "pierde" : ""}`}>{cob == null ? "n/d" : `${cob}%`}</span>
|
||||||
|
<span className="l">vs. promedio renovado últimos 3 meses ({money(histProm)})</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi"><span className="n pierde">{estanc.length}</span><span className="l">En riesgo (estancadas)</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={`callout ${cob != null && cob < 100 ? "warn" : "info"}`}>
|
||||||
|
{win === ATRASADAS ? (
|
||||||
|
<><b>Estas {p.length} renovaciones ya pasaron su fecha estimada y siguen abiertas.</b> En renovación el
|
||||||
|
tiempo juega en contra de forma literal: el contrato vence igual, con o sin gestión. </>
|
||||||
|
) : (
|
||||||
|
<><b>{winLbl}: {money(est)} de MRR vence este mes</b> en {p.length} contratos, con un forecast ponderado
|
||||||
|
de {money(fc)}. </>
|
||||||
|
)}
|
||||||
|
<b>Acá no se compara contra meta</b> — la meta comercial no incluye renovaciones. La referencia útil es lo
|
||||||
|
que se renovó de verdad en los 3 meses anteriores ({money(histProm)} en promedio). <b>Forecast ponderado =
|
||||||
|
Σ (MRR × peso del Plan de Cierre)</b>: A 90% · B 60% · C 30% · sin plan 10%.
|
||||||
|
</div>
|
||||||
|
{sinPlan.length > 0 && (
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>{sinPlan.length} de estas {p.length} no tienen Plan de Cierre</b> ({money(sinPlan.reduce((a, o) => a + o.est, 0))}).
|
||||||
|
A diferencia de Previsión de Ventas —que las excluye por no tener compromiso real— acá <b>se cuentan
|
||||||
|
igual</b>: el contrato vence tenga plan o no, y esconderlas sería esconder el riesgo. Pesan solo 10% en el
|
||||||
|
ponderado, así que el forecast las subestima a propósito.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{porMes.length > 1 && (
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>Vencimientos por delante:</b> {porMes.map((m) => `${m.lbl} — ${money(m.est)} (${m.n})`).join(" · ")}.
|
||||||
|
Empezar la gestión el mes anterior es lo que mueve la renovación de «tarde» a «a tiempo».
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{p.length > 0 && <ExecMatrix arr={p} titulo="Renovaciones por vencer, por ejecutivo" hint="Monto = MRR en juego" activeDim={mze} />}
|
||||||
|
|
||||||
|
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
{pWin.length === 0 ? (
|
||||||
|
<p>No hay renovaciones en esta ventana.</p>
|
||||||
|
) : (
|
||||||
|
<div className="split23">
|
||||||
|
<div className="split23-ind">
|
||||||
|
<Panel
|
||||||
|
title="Por momento de la renovación"
|
||||||
|
hint="Ya vencido vs. próximo a vencer"
|
||||||
|
rows={agg(p, "tipo", (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="tipo"
|
||||||
|
/>
|
||||||
|
<Panel
|
||||||
|
title="¿Ya se agendó algo?"
|
||||||
|
hint={`Tarea/Cita/Llamada dentro de ${winLbl}`}
|
||||||
|
rows={aggOrd(p, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="actAgendada"
|
||||||
|
/>
|
||||||
|
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||||
|
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title={IND_TITULOS[indActive]}
|
||||||
|
hint={IND_HINTS[indActive]}
|
||||||
|
rows={agg(p, indActive, (o) => o.est)}
|
||||||
|
top={IND_TOP[indActive]}
|
||||||
|
dimKey={indActive}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Renovaciones con vencimiento en {winLbl}</h3>
|
||||||
|
<p className="hint">Forecast = MRR × peso del plan · scroll horizontal con la columna fija · clic en el nombre abre Dynamics</p>
|
||||||
|
</div>
|
||||||
|
<TablaPipe arr={p} tipo="fc" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/renovaciones/tuberia/loading.js
Normal file
4
app/renovaciones/tuberia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
155
app/renovaciones/tuberia/page.js
Normal file
155
app/renovaciones/tuberia/page.js
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
import { auth } from "../../lib/auth";
|
||||||
|
import { ownerFilter } from "../../lib/authz";
|
||||||
|
import { getRenovPipeline, getSystemUsers, getActividades } from "../../lib/queries";
|
||||||
|
import LoginPrompt from "../../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../../components/ErrorNotice";
|
||||||
|
import Panel from "../../components/pipeline/Panel";
|
||||||
|
import TablaPipe from "../../components/pipeline/TablaPipe";
|
||||||
|
import ExecMatrix from "../../components/pipeline/ExecMatrix";
|
||||||
|
import SegTabs from "../../components/SegTabs";
|
||||||
|
import FilterChips from "../../components/FilterChips";
|
||||||
|
import { money } from "../../lib/constants";
|
||||||
|
import { EJECUTIVOS_RENOV, agg, aggOrd, cierreVencido, decorarActividadVentana, ACTAGENDADA_ORDEN } from "../../lib/derive";
|
||||||
|
import { parseFiltParam, applyFilt } from "../../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const IND_TABS = [
|
||||||
|
{ k: "owner", lbl: "Ejecutivo" },
|
||||||
|
{ k: "cliente", lbl: "Cliente" },
|
||||||
|
{ k: "linea", lbl: "Línea" },
|
||||||
|
{ k: "competidor", lbl: "Competidor" },
|
||||||
|
];
|
||||||
|
const IND_TITULOS = {
|
||||||
|
owner: "Por Ejecutivo",
|
||||||
|
cliente: "Por Cliente",
|
||||||
|
linea: "Por Línea de Negocio",
|
||||||
|
competidor: "Por Competidor",
|
||||||
|
};
|
||||||
|
const IND_HINTS = {
|
||||||
|
owner: "Ordenado por MRR en juego",
|
||||||
|
cliente: "Las cuentas con más MRR por renovar",
|
||||||
|
linea: "Ordenado por MRR en juego",
|
||||||
|
competidor: "Contra quién se compite la renovación",
|
||||||
|
};
|
||||||
|
const IND_TOP = { owner: undefined, cliente: 7, linea: undefined, competidor: 7 };
|
||||||
|
const DIM_LABELS = { owner: "Ejecutivo", cliente: "Cliente", linea: "Línea", competidor: "Competidor", tipo: "Momento", actAgendada: "Agendado" };
|
||||||
|
|
||||||
|
export default async function RenovTuberiaPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "owner";
|
||||||
|
const mze = sp.mze;
|
||||||
|
|
||||||
|
let pipelineRows, allUsers, actividades;
|
||||||
|
try {
|
||||||
|
[pipelineRows, allUsers, actividades] = await Promise.all([
|
||||||
|
getRenovPipeline(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
getActividades(session.accessToken, scope, EJECUTIVOS_RENOV),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_RENOV.includes(u.name));
|
||||||
|
const hoy = new Date().toISOString().slice(0, 10);
|
||||||
|
const allRows = decorarActividadVentana(pipelineRows, actividades, hoy, "9999-12-31");
|
||||||
|
const rows = applyFilt(allRows, filt);
|
||||||
|
|
||||||
|
const totalEst = rows.reduce((a, r) => a + r.est, 0);
|
||||||
|
const totalFc = rows.reduce((a, r) => a + r.fc, 0);
|
||||||
|
const estanc = rows.filter((r) => r.estanc);
|
||||||
|
const estancEst = estanc.reduce((a, r) => a + r.est, 0);
|
||||||
|
const sinPlan = rows.filter((r) => r.plan === "Sin plan de cierre");
|
||||||
|
const sinPlanEst = sinPlan.reduce((a, r) => a + r.est, 0);
|
||||||
|
const vencidas = rows.filter(cierreVencido);
|
||||||
|
const yaVencido = rows.filter((r) => r.tipo === "Contrato vencido");
|
||||||
|
const pctSinPlan = rows.length ? Math.round((sinPlan.length / rows.length) * 100) : 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Tubería de Renovaciones</h2>
|
||||||
|
<OwnerControl owners={owners} current={scope.locked ? session.email : scope.email} locked={scope.locked} lockedLabel={session.email} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi"><span className="n">{money(totalEst)}</span><span className="l">MRR en juego (est.)</span></div>
|
||||||
|
<div className="kpi"><span className="n">{rows.length}</span><span className="l">Renovaciones abiertas</span></div>
|
||||||
|
<div className="kpi"><span className="n">{money(totalFc)}</span><span className="l">Forecast ponderado</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{yaVencido.length}</span><span className="l">Con el contrato YA vencido · {money(yaVencido.reduce((a, o) => a + o.est, 0))}</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{estanc.length}</span><span className="l">Estancadas · {money(estancEst)}</span></div>
|
||||||
|
<div className="kpi"><span className="n pierde">{sinPlan.length}</span><span className="l">Sin plan de cierre · {money(sinPlanEst)}</span></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{rows.length === 0 ? (
|
||||||
|
<p>No hay renovaciones activas para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>Esto no es pipeline nuevo: es MRR que ya está facturando y hay que no perder.</b> Hay <b>{money(totalEst)}</b> en{" "}
|
||||||
|
{rows.length} renovaciones abiertas, de las cuales <b>{yaVencido.length} ya tienen el contrato vencido</b> —
|
||||||
|
ahí el cliente está sin amarre y expuesto a que lo llame la competencia. <b>{estanc.length} de {rows.length}</b>{" "}
|
||||||
|
están estancadas (+14 días sin actividad o +30 en la misma fase) por {money(estancEst)}, y{" "}
|
||||||
|
<b>{vencidas.length}</b> pasaron su fecha estimada de cierre.
|
||||||
|
</div>
|
||||||
|
{pctSinPlan > 50 && (
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>{pctSinPlan}% de la tubería de renovaciones no tiene Plan de Cierre</b> ({sinPlan.length} de{" "}
|
||||||
|
{rows.length}, {money(sinPlanEst)}). Sin plan, el forecast ponderado les asigna apenas 10% y el número
|
||||||
|
de abajo queda subestimado — pero el problema de fondo no es el cálculo: es que {sinPlan.length}{" "}
|
||||||
|
contratos que vencen no tienen una fecha de firma comprometida.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<ExecMatrix arr={rows} titulo="Renovaciones por ejecutivo" hint="Incluye Ventas y SAC" activeDim={mze} />
|
||||||
|
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
<div className="split23">
|
||||||
|
<div className="split23-ind">
|
||||||
|
<Panel
|
||||||
|
title="Por momento de la renovación"
|
||||||
|
hint="Ya vencido vs. próximo a vencer"
|
||||||
|
rows={agg(rows, "tipo", (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="tipo"
|
||||||
|
/>
|
||||||
|
<Panel
|
||||||
|
title="¿Ya se agendó algo?"
|
||||||
|
hint="Tarea/Cita/Llamada desde hoy en adelante"
|
||||||
|
rows={aggOrd(rows, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="actAgendada"
|
||||||
|
/>
|
||||||
|
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||||
|
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title={IND_TITULOS[indActive]}
|
||||||
|
hint={IND_HINTS[indActive]}
|
||||||
|
rows={agg(rows, indActive, (o) => o.est)}
|
||||||
|
top={IND_TOP[indActive]}
|
||||||
|
dimKey={indActive}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de la tubería de renovaciones</h3>
|
||||||
|
<p className="hint">
|
||||||
|
Scroll horizontal con la columna Cliente/Oportunidad fija · <b>Plan</b>: A en firma · B negociación
|
||||||
|
· C seguimiento · D recalificar · ⚠ cierre vencido · clic en el nombre abre Dynamics
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<TablaPipe arr={rows} tipo="est" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/resumen/loading.js
Normal file
4
app/resumen/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
129
app/resumen/page.js
Normal file
129
app/resumen/page.js
Normal file
|
|
@ -0,0 +1,129 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getClosed, getMotivosCierre, getSystemUsers } from "../lib/queries";
|
||||||
|
import { TIPOS_META, EJECUTIVOS_VENTA } from "../lib/derive";
|
||||||
|
import { getMetas, getMetaGlobal } from "../lib/metas";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import DashBar from "../components/pipeline/DashBar";
|
||||||
|
import DashDonut from "../components/pipeline/DashDonut";
|
||||||
|
import WonTable from "../components/pipeline/WonTable";
|
||||||
|
import { money2 } from "../lib/constants";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
function currentMonth() {
|
||||||
|
const d = new Date();
|
||||||
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function ResumenPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const mes = currentMonth();
|
||||||
|
|
||||||
|
let wonRaw, lost, allUsers;
|
||||||
|
try {
|
||||||
|
[wonRaw, lost, allUsers] = await Promise.all([
|
||||||
|
getClosed(session.accessToken, scope, 1, mes),
|
||||||
|
getClosed(session.accessToken, scope, 2, mes),
|
||||||
|
getSystemUsers(session.accessToken),
|
||||||
|
]);
|
||||||
|
const motivos = await getMotivosCierre(lost.map((o) => o.id), session.accessToken);
|
||||||
|
lost = lost.map((o) => ({ ...o, motivo: motivos[o.id]?.motivo || "Sin registrar" }));
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
// val en vez de actual, para que DashBar/DashDonut/WonTable (compartidos con Nuevas Oportunidades)
|
||||||
|
// no necesiten dos convenciones de nombre de campo distintas.
|
||||||
|
const won = wonRaw.map((o) => ({ ...o, val: o.actual }));
|
||||||
|
|
||||||
|
const sumW = won.reduce((a, o) => a + (o.val || 0), 0);
|
||||||
|
const sumWMeta = won
|
||||||
|
.filter((o) => TIPOS_META.includes(o.tipo))
|
||||||
|
.reduce((a, o) => a + (o.val || 0), 0);
|
||||||
|
const arpu = won.length ? sumW / won.length : 0;
|
||||||
|
|
||||||
|
// Tasa de Ganancia Total (todo el denominador) vs. Real (excluye depuración de datos, que no es
|
||||||
|
// pérdida de negocio real) — ver CLAUDE.md, lección "el forecast ponderado sobreestima" /
|
||||||
|
// hallazgo Win Rate. Replicado de pages/resumen.js del sitio HTML.
|
||||||
|
const depuN = lost.filter((o) => o.motivo === "Descartada sin motivo (depuración)").length;
|
||||||
|
const lostRealN = lost.length - depuN;
|
||||||
|
const convTotal = won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0;
|
||||||
|
const convReal = won.length + lostRealN ? Math.round((won.length / (won.length + lostRealN)) * 100) : 0;
|
||||||
|
|
||||||
|
const metas = getMetas();
|
||||||
|
const viewedEmail = scope.locked ? session.email : scope.email;
|
||||||
|
const metaDen = viewedEmail ? metas[viewedEmail.toLowerCase()] || null : getMetaGlobal();
|
||||||
|
const cumpl = metaDen ? Math.round((sumWMeta / metaDen) * 100) : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Resumen — {mes}</h2>
|
||||||
|
<OwnerControl
|
||||||
|
owners={owners}
|
||||||
|
current={scope.locked ? session.email : scope.email}
|
||||||
|
locked={scope.locked}
|
||||||
|
lockedLabel={session.email}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money2(sumW)}</span>
|
||||||
|
<span className="l">Ingresos Reales (ganadas)</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{won.length}</span>
|
||||||
|
<span className="l">Oportunidades ganadas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money2(arpu)}</span>
|
||||||
|
<span className="l">ARPU logradas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{lost.length}</span>
|
||||||
|
<span className="l">Oportunidades perdidas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{convTotal}%</span>
|
||||||
|
<span className="l">Tasa de Ganancia Total</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi" title={`Excluye ${depuN} pérdida(s) descartadas sin motivo real (depuración de datos)`}>
|
||||||
|
<span className="n">{convReal}%</span>
|
||||||
|
<span className="l">Tasa de Ganancia Real</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className={cumpl != null && cumpl < 70 ? "n pierde" : "n"}>
|
||||||
|
{cumpl != null ? cumpl + "%" : "n/d"}
|
||||||
|
</span>
|
||||||
|
<span className="l">
|
||||||
|
Cumplimiento de meta{metaDen ? ` (${money2(metaDen)})` : " (sin meta asignada)"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="hint">
|
||||||
|
Cumplimiento de meta cuenta solo Venta - Cliente Nuevo, Up-Selling, Cross-Selling y Plan de Cuenta (se
|
||||||
|
excluyen renovaciones y SAC).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="grid2">
|
||||||
|
<DashBar title="Propietario" arr={won} dimKey="owner" />
|
||||||
|
<DashBar title="Línea de Negocio" arr={won} dimKey="linea" />
|
||||||
|
<DashBar title="Tipo de Oportunidad" arr={won} dimKey="tipo" />
|
||||||
|
<DashDonut title="Segmento" arr={won} dimKey="segmento" />
|
||||||
|
<DashBar title="Origen de Oportunidad" arr={won} dimKey="origen" />
|
||||||
|
<DashBar title="Ventas por Campaña de Origen" arr={won} dimKey="campaign" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<WonTable rows={won} title="Detalle de Oportunidades Ganadas" locked={scope.locked} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/tendencia/loading.js
Normal file
4
app/tendencia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
115
app/tendencia/page.js
Normal file
115
app/tendencia/page.js
Normal file
|
|
@ -0,0 +1,115 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getClosed, resolveScopeOwnerId } from "../lib/queries";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import { money, money2 } from "../lib/constants";
|
||||||
|
import { getMetaGlobal } from "../lib/metas";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const MESES_A_MOSTRAR = 6;
|
||||||
|
|
||||||
|
function lastMonths(n) {
|
||||||
|
const out = [];
|
||||||
|
const d = new Date();
|
||||||
|
for (let i = n - 1; i >= 0; i--) {
|
||||||
|
const dt = new Date(d.getFullYear(), d.getMonth() - i, 1);
|
||||||
|
out.push(`${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, "0")}`);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function TendenciaPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const { owner } = await searchParams;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const meses = lastMonths(MESES_A_MOSTRAR);
|
||||||
|
|
||||||
|
const metaGlobal = getMetaGlobal();
|
||||||
|
let porMes;
|
||||||
|
try {
|
||||||
|
const { ownerId } = await resolveScopeOwnerId(scope, session.accessToken);
|
||||||
|
porMes = await Promise.all(
|
||||||
|
meses.map(async (m) => {
|
||||||
|
const [won, lost] = await Promise.all([
|
||||||
|
getClosed(session.accessToken, scope, 1, m, ownerId),
|
||||||
|
getClosed(session.accessToken, scope, 2, m, ownerId),
|
||||||
|
]);
|
||||||
|
const sumW = won.reduce((a, o) => a + (o.actual || 0), 0);
|
||||||
|
return {
|
||||||
|
mes: m,
|
||||||
|
won: won.length,
|
||||||
|
lost: lost.length,
|
||||||
|
sumW,
|
||||||
|
arpu: won.length ? sumW / won.length : 0,
|
||||||
|
conv: won.length + lost.length ? Math.round((won.length / (won.length + lost.length)) * 100) : 0,
|
||||||
|
cumpl: metaGlobal ? Math.round((sumW / metaGlobal) * 100) : null,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxSumW = Math.max(...porMes.map((m) => m.sumW), 1);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<h2>Tendencia</h2>
|
||||||
|
<p className="hint" style={{ marginBottom: 16 }}>
|
||||||
|
Últimos {MESES_A_MOSTRAR} meses, calculado en vivo desde Dynamics. No incluye el análisis narrativo del
|
||||||
|
tablero anterior (era específico de un semestre puntual) — solo las cifras.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="panel">
|
||||||
|
<h3>Ganadas ($) por mes</h3>
|
||||||
|
{porMes.map((m) => (
|
||||||
|
<div className="row static" key={m.mes}>
|
||||||
|
<div className="bl">
|
||||||
|
<span className="nm">{m.mes}</span>
|
||||||
|
</div>
|
||||||
|
<div className="bar-cell">
|
||||||
|
<div className="bar-fill" style={{ width: `${((m.sumW / maxSumW) * 100).toFixed(1)}%` }} />
|
||||||
|
</div>
|
||||||
|
<span className="v">{m.won}</span>
|
||||||
|
<span className="c">{money(m.sumW)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="tw" style={{ marginTop: 18 }}>
|
||||||
|
<div className="ts">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Mes</th>
|
||||||
|
<th className="num">Ganadas #</th>
|
||||||
|
<th className="num">Ganadas $</th>
|
||||||
|
<th className="num">ARPU</th>
|
||||||
|
<th className="num">Perdidas #</th>
|
||||||
|
<th className="num">Conversión</th>
|
||||||
|
<th className="num">Cumpl. (meta {money(metaGlobal)})</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{porMes.map((m) => (
|
||||||
|
<tr key={m.mes}>
|
||||||
|
<td>{m.mes}</td>
|
||||||
|
<td className="num">{m.won}</td>
|
||||||
|
<td className="num">{money2(m.sumW)}</td>
|
||||||
|
<td className="num">{money2(m.arpu)}</td>
|
||||||
|
<td className="num">{m.lost}</td>
|
||||||
|
<td className="num">{m.conv}%</td>
|
||||||
|
<td className="num">{m.cumpl != null ? `${m.cumpl}%` : "n/d"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
4
app/tuberia/loading.js
Normal file
4
app/tuberia/loading.js
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
import PageLoading from "../components/PageLoading";
|
||||||
|
export default function Loading() {
|
||||||
|
return <PageLoading />;
|
||||||
|
}
|
||||||
169
app/tuberia/page.js
Normal file
169
app/tuberia/page.js
Normal file
|
|
@ -0,0 +1,169 @@
|
||||||
|
import { auth } from "../lib/auth";
|
||||||
|
import { ownerFilter } from "../lib/authz";
|
||||||
|
import { getPipeline, getSystemUsers, getActividades } from "../lib/queries";
|
||||||
|
import LoginPrompt from "../components/LoginPrompt";
|
||||||
|
import OwnerControl from "../components/OwnerControl";
|
||||||
|
import ErrorNotice from "../components/ErrorNotice";
|
||||||
|
import Panel from "../components/pipeline/Panel";
|
||||||
|
import MatrizCalidad from "../components/pipeline/MatrizCalidad";
|
||||||
|
import TablaPipe from "../components/pipeline/TablaPipe";
|
||||||
|
import ExecMatrix from "../components/pipeline/ExecMatrix";
|
||||||
|
import SegTabs from "../components/SegTabs";
|
||||||
|
import FilterChips from "../components/FilterChips";
|
||||||
|
import { money } from "../lib/constants";
|
||||||
|
import { EJECUTIVOS_VENTA, agg, aggOrd, hayClasif, cierreVencido, decorarActividadVentana, ACTAGENDADA_ORDEN } from "../lib/derive";
|
||||||
|
import { parseFiltParam, applyFilt } from "../lib/filterState";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
const IND_TABS = [
|
||||||
|
{ k: "tipo", lbl: "Tipo" },
|
||||||
|
{ k: "origen", lbl: "Origen" },
|
||||||
|
{ k: "competidor", lbl: "Competidor" },
|
||||||
|
{ k: "linea", lbl: "Línea" },
|
||||||
|
{ k: "servicio", lbl: "Servicio" },
|
||||||
|
];
|
||||||
|
const IND_TITULOS = {
|
||||||
|
tipo: "Por Tipo de Oportunidad",
|
||||||
|
origen: "Por Origen de Oportunidad",
|
||||||
|
competidor: "Por Competidor",
|
||||||
|
linea: "Por Línea de Negocio",
|
||||||
|
servicio: "Por Servicio / Producto",
|
||||||
|
};
|
||||||
|
const IND_TOP = { tipo: undefined, origen: 7, competidor: 7, linea: undefined, servicio: 7 };
|
||||||
|
const DIM_LABELS = { tipo: "Tipo", origen: "Origen", competidor: "Competidor", linea: "Línea", servicio: "Servicio", luz: "Luz Amarilla", calidad: "Calidad", mov: "Movimiento", actAgendada: "Agendado" };
|
||||||
|
|
||||||
|
export default async function TuberiaPage({ searchParams }) {
|
||||||
|
const session = await auth();
|
||||||
|
if (!session?.email) return <LoginPrompt />;
|
||||||
|
|
||||||
|
const sp = await searchParams;
|
||||||
|
const { owner } = sp;
|
||||||
|
const scope = ownerFilter(session, owner);
|
||||||
|
const filt = parseFiltParam(sp.f);
|
||||||
|
const indActive = IND_TABS.some((t) => t.k === sp.ind) ? sp.ind : "tipo";
|
||||||
|
const mze = sp.mze;
|
||||||
|
|
||||||
|
let pipelineRows, allUsers, actividades;
|
||||||
|
try {
|
||||||
|
[pipelineRows, allUsers, actividades] = await Promise.all([
|
||||||
|
getPipeline(session.accessToken, scope),
|
||||||
|
session.isAdmin ? getSystemUsers(session.accessToken) : Promise.resolve([]),
|
||||||
|
getActividades(session.accessToken, scope),
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
return <ErrorNotice error={error} />;
|
||||||
|
}
|
||||||
|
const owners = allUsers.filter((u) => EJECUTIVOS_VENTA.includes(u.name));
|
||||||
|
// Ventana abierta (desde hoy en adelante, sin tope): Tubería no tiene selector de período, así
|
||||||
|
// que la pregunta es "¿ya se planeó algo para moverla, sea cuando sea?" (ver utils.js del HTML).
|
||||||
|
const hoy = new Date().toISOString().slice(0, 10);
|
||||||
|
const allRows = decorarActividadVentana(pipelineRows, actividades, hoy, "9999-12-31");
|
||||||
|
const rows = applyFilt(allRows, filt);
|
||||||
|
|
||||||
|
const sorted = [...rows].sort((a, b) => b.est - a.est);
|
||||||
|
const totalEst = rows.reduce((a, r) => a + r.est, 0);
|
||||||
|
const totalFc = rows.reduce((a, r) => a + r.fc, 0);
|
||||||
|
const estanc = rows.filter((r) => r.estanc);
|
||||||
|
const estancadas = estanc.length;
|
||||||
|
const estancEst = estanc.reduce((a, r) => a + r.est, 0);
|
||||||
|
const sinPlan = rows.filter((r) => r.plan === "Sin plan de cierre");
|
||||||
|
const sinPlanEst = sinPlan.reduce((a, r) => a + r.est, 0);
|
||||||
|
const vencidas = rows.filter(cierreVencido);
|
||||||
|
const enOfertaONegociacion = rows.filter((r) => r.faseActual === "Oferta" || r.faseActual === "Negociación").length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 24 }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 12 }}>
|
||||||
|
<h2>Tubería Activa</h2>
|
||||||
|
<OwnerControl
|
||||||
|
owners={owners}
|
||||||
|
current={scope.locked ? session.email : scope.email}
|
||||||
|
locked={scope.locked}
|
||||||
|
lockedLabel={session.email}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="kpis">
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{rows.length}</span>
|
||||||
|
<span className="l">Oportunidades activas</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money(totalEst)}</span>
|
||||||
|
<span className="l">Estimado total</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n">{money(totalFc)}</span>
|
||||||
|
<span className="l">Forecast ponderado</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{estancadas}</span>
|
||||||
|
<span className="l">Estancadas (>14d sin actividad o >30d en fase)</span>
|
||||||
|
</div>
|
||||||
|
<div className="kpi">
|
||||||
|
<span className="n pierde">{sinPlan.length}</span>
|
||||||
|
<span className="l">Sin plan de cierre · {money(sinPlanEst)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{sorted.length === 0 ? (
|
||||||
|
<p>No hay oportunidades activas para este filtro.</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="callout warn">
|
||||||
|
<b>¿Qué es estancamiento?</b> Una oportunidad está estancada si lleva <b>más de 14 días sin ninguna
|
||||||
|
actividad</b> (llamada/cita/correo) <b>o más de 30 días atascada en la misma fase</b>. Hoy hay{" "}
|
||||||
|
<b>{estancadas} de {rows.length}</b> así ({rows.length ? Math.round((estancadas / rows.length) * 100) : 0}%) —{" "}
|
||||||
|
{money(estancEst)} de MRR sin movimiento. <b>{vencidas.length}</b> ya pasaron su fecha estimada de cierre.
|
||||||
|
Y <b>{enOfertaONegociacion}</b> de {rows.length} están en Oferta o Negociación: el embudo está cargado al
|
||||||
|
final — casi no entra nada nuevo por arriba.
|
||||||
|
</div>
|
||||||
|
<ExecMatrix arr={rows} titulo="Tubería por ejecutivo" activeDim={mze} />
|
||||||
|
<div className="sec-div"><span>Indicadores y detalle</span></div>
|
||||||
|
<FilterChips dimLabels={DIM_LABELS} />
|
||||||
|
<div className="split23">
|
||||||
|
<div className="split23-ind">
|
||||||
|
{hayClasif(rows) && <MatrizCalidad arr={rows} />}
|
||||||
|
<Panel
|
||||||
|
title="Luz Amarilla — qué la detiene"
|
||||||
|
hint="Bloqueador declarado por el ejecutivo"
|
||||||
|
rows={agg(rows, "luz", (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
top={7}
|
||||||
|
dimKey="luz"
|
||||||
|
/>
|
||||||
|
<Panel
|
||||||
|
title="¿Ya se agendó algo?"
|
||||||
|
hint="Tarea/Cita/Llamada desde hoy en adelante"
|
||||||
|
rows={aggOrd(rows, "actAgendada", ACTAGENDADA_ORDEN, (o) => o.est)}
|
||||||
|
cls="alerta"
|
||||||
|
dimKey="actAgendada"
|
||||||
|
/>
|
||||||
|
<div className="panel" style={{ paddingBottom: 4 }}>
|
||||||
|
<SegTabs tabs={IND_TABS} activeKey={indActive} paramName="ind" />
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title={IND_TITULOS[indActive]}
|
||||||
|
rows={agg(rows, indActive, (o) => o.est)}
|
||||||
|
top={IND_TOP[indActive]}
|
||||||
|
dimKey={indActive}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="panel" style={{ paddingBottom: 6 }}>
|
||||||
|
<h3>Detalle de la tubería activa</h3>
|
||||||
|
<p className="hint">
|
||||||
|
Scroll horizontal con la columna Cliente/Oportunidad fija · <b>Plan</b>: A en firma · B negociación
|
||||||
|
· C seguimiento · D recalificar · <b>Actividad</b>: ● verde activa, ámbar tibia, naranja fría, rojo
|
||||||
|
congelada · ⚠ cierre vencido · clic en el nombre abre Dynamics
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<TablaPipe arr={rows} tipo="est" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
7
next.config.js
Normal file
7
next.config.js
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {
|
||||||
|
output: "standalone",
|
||||||
|
serverExternalPackages: ["better-sqlite3"],
|
||||||
|
images: { unoptimized: true },
|
||||||
|
};
|
||||||
|
module.exports = nextConfig;
|
||||||
1138
package-lock.json
generated
Normal file
1138
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
20
package.json
Normal file
20
package.json
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
{
|
||||||
|
"name": "informe-comercial",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"better-sqlite3": "^13.0.3",
|
||||||
|
"next": "^16.3.5",
|
||||||
|
"next-auth": "^5.0.0-beta.32",
|
||||||
|
"react": "19.0.0",
|
||||||
|
"react-dom": "19.0.0"
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"better-sqlite3@11.8.1": true
|
||||||
|
}
|
||||||
|
}
|
||||||
13
public/assets/css/base.css
Normal file
13
public/assets/css/base.css
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
@font-face{font-family:'Ubuntu Sans';font-weight:400;font-style:normal;src:url(../fonts/UbuntuSans-Regular.ttf) format('truetype');}
|
||||||
|
@font-face{font-family:'Ubuntu Sans';font-weight:700;font-style:normal;src:url(../fonts/UbuntuSans-Bold.ttf) format('truetype');}
|
||||||
|
:root{
|
||||||
|
--marca:#1E71B8; --ancla:#01205B; --profundo:#134766; --palido:#D1EBF7; --gris:#F2F3F4;
|
||||||
|
--tinta:#0e1c2b; --tinta-suave:#5a6b7a; --linea:#dfe4ea; --panel:#ffffff;
|
||||||
|
--gana:#1E71B8; --gana-soft:#dbeaf6; --pierde:#B23A2E; --pierde-soft:#f6e2de; --alerta:#C98A1B; --alerta-soft:#f7edd6;
|
||||||
|
--profundo-soft:#dbe6ea;
|
||||||
|
--sans:'Ubuntu Sans',-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
|
||||||
|
--mono:'SF Mono','Cascadia Code',Consolas,monospace;
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box;}
|
||||||
|
body{margin:0;background:var(--gris);color:var(--tinta);font-family:var(--sans);line-height:1.45;-webkit-font-smoothing:antialiased;}
|
||||||
|
select{font-family:var(--sans);font-size:13px;padding:6px 10px;border:1px solid var(--linea);border-radius:6px;background:#fff;color:var(--tinta);cursor:pointer;}
|
||||||
371
public/assets/css/components.css
Normal file
371
public/assets/css/components.css
Normal file
|
|
@ -0,0 +1,371 @@
|
||||||
|
.ctrl{display:flex;align-items:center;gap:8px;}
|
||||||
|
.ctrl label{font-size:10.5px;text-transform:uppercase;letter-spacing:.06em;color:var(--tinta-suave);font-weight:700;}
|
||||||
|
/* owner multi-select */
|
||||||
|
.owner-ctrl{position:relative;}
|
||||||
|
.owner-btn{font-family:var(--sans);font-size:13px;padding:6px 10px;border:1px solid var(--linea);border-radius:6px;background:#fff;color:var(--tinta);cursor:pointer;min-width:150px;text-align:left;display:inline-flex;justify-content:space-between;align-items:center;gap:10px;}
|
||||||
|
.owner-btn:after{content:'▾';font-size:10px;color:var(--tinta-suave);}
|
||||||
|
.owner-btn:disabled{cursor:default;opacity:.85;}
|
||||||
|
.owner-btn:disabled:after{content:'';}
|
||||||
|
.owner-panel{display:none;position:absolute;top:calc(100% + 6px);right:0;background:#fff;border:1px solid var(--linea);border-radius:8px;box-shadow:0 8px 24px rgba(1,32,91,.18);padding:8px;min-width:250px;max-height:340px;overflow-y:auto;z-index:15;}
|
||||||
|
.owner-panel.open{display:block;}
|
||||||
|
.owner-panel .oa{display:flex;gap:10px;flex-wrap:wrap;padding:2px 6px 8px;border-bottom:1px solid var(--linea);margin-bottom:4px;}
|
||||||
|
.owner-panel .oa a{font-size:11px;color:var(--marca);cursor:pointer;text-decoration:none;font-weight:700;}
|
||||||
|
.owner-panel .oa a:hover{text-decoration:underline;}
|
||||||
|
.owner-panel .owner-row{display:flex;align-items:center;gap:8px;padding:5px 6px;border-radius:5px;font-size:12.5px;text-transform:none;letter-spacing:normal;font-weight:400;color:var(--tinta);cursor:pointer;}
|
||||||
|
.owner-row:hover{background:var(--gana-soft);}
|
||||||
|
.owner-row input{cursor:pointer;}
|
||||||
|
/* buscador global de cliente/oportunidad (search.js) — mismo patrón que owner-ctrl/owner-panel */
|
||||||
|
.search-ctrl{position:relative;}
|
||||||
|
.search-input{font-family:var(--sans);font-size:13px;padding:6px 10px;border:1px solid var(--linea);border-radius:6px;background:#fff;color:var(--tinta);width:230px;}
|
||||||
|
.search-input:focus{outline:none;border-color:var(--marca);}
|
||||||
|
.search-panel{display:none;position:absolute;top:calc(100% + 6px);right:0;background:#fff;border:1px solid var(--linea);border-radius:8px;box-shadow:0 8px 24px rgba(1,32,91,.18);width:340px;max-width:calc(100vw - 32px);max-height:380px;overflow-y:auto;z-index:16;}
|
||||||
|
/* Angosto: anclar por la izquierda en vez de por la derecha — a este ancho el control de búsqueda
|
||||||
|
queda cerca del borde izquierdo (el resto del topbar se apila debajo por el flex-wrap), así que
|
||||||
|
anclar por la derecha sacaba el panel de pantalla. */
|
||||||
|
@media (max-width:600px){
|
||||||
|
.search-panel{right:auto;left:0;width:min(320px,calc(100vw - 40px));}
|
||||||
|
}
|
||||||
|
.search-panel.open{display:block;}
|
||||||
|
.search-empty{padding:12px;font-size:12px;color:var(--tinta-suave);}
|
||||||
|
.search-row{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 12px;border-bottom:1px solid var(--linea);text-decoration:none;color:inherit;}
|
||||||
|
.search-row:last-child{border-bottom:none;}
|
||||||
|
.search-row:hover{background:var(--gana-soft);}
|
||||||
|
.search-row-main{display:flex;flex-direction:column;gap:2px;min-width:0;}
|
||||||
|
.search-row-main .nm{font-size:12.5px;font-weight:700;color:var(--ancla);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:220px;}
|
||||||
|
.search-row-main .cli{font-size:10.5px;color:var(--tinta-suave);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:220px;}
|
||||||
|
.search-row-meta{display:flex;flex-direction:column;align-items:flex-end;gap:3px;flex-shrink:0;}
|
||||||
|
.search-row-meta .v{font-family:var(--mono);font-size:11px;color:var(--tinta-suave);}
|
||||||
|
.pill.neutro{background:var(--palido);color:var(--profundo);}
|
||||||
|
/* login button (auth.js) */
|
||||||
|
.login-btn{font-family:var(--sans);font-size:13px;padding:6px 14px;border:1px solid var(--marca);border-radius:6px;background:var(--marca);color:#fff;cursor:pointer;font-weight:700;text-decoration:none;display:inline-block;}
|
||||||
|
.login-btn:hover{opacity:.9;}
|
||||||
|
/* filter chips */
|
||||||
|
.chips{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:18px;min-height:26px;align-items:center;}
|
||||||
|
.chips .lbl{font-family:var(--mono);font-size:10.5px;text-transform:uppercase;letter-spacing:.06em;color:var(--tinta-suave);}
|
||||||
|
.chip{font-size:12px;background:var(--gana-soft);color:var(--profundo);border:1px solid var(--marca);border-radius:13px;padding:4px 11px;cursor:pointer;}
|
||||||
|
.chip.clear{background:none;border-color:var(--tinta-suave);color:var(--tinta-suave);}
|
||||||
|
.chip-empty{font-size:12.5px;color:var(--tinta-suave);font-style:italic;}
|
||||||
|
/* kpi */
|
||||||
|
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px;margin-bottom:22px;}
|
||||||
|
.kpi{background:var(--panel);border:1px solid var(--linea);border-radius:10px;padding:16px 18px;display:flex;flex-direction:column;gap:5px;box-shadow:0 1px 2px rgba(1,32,91,.05),0 2px 8px rgba(1,32,91,.04);}
|
||||||
|
.kpi .n{font-size:27px;font-weight:700;color:var(--ancla);line-height:1;font-variant-numeric:tabular-nums;}
|
||||||
|
.kpi .n.pierde{color:var(--pierde);}
|
||||||
|
.kpi .l{font-size:11.5px;color:var(--tinta-suave);}
|
||||||
|
.kpi .d{font-size:11px;font-variant-numeric:tabular-nums;}
|
||||||
|
.kpi .d.up{color:var(--gana);} .kpi .d.down{color:var(--pierde);}
|
||||||
|
/* Descomposición volumen × ticket (página Tendencia) — el cambio de ingreso solo puede venir de dos
|
||||||
|
lugares: cuántos negocios se cerraron y qué tan grande fue cada uno. El panel tiene que dejar ver
|
||||||
|
cuál de los dos mandó, de un vistazo. */
|
||||||
|
.tdesc-tot{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;padding-bottom:12px;border-bottom:1px solid var(--linea);margin-bottom:14px;}
|
||||||
|
.tdesc-tot .val{font-size:17px;font-weight:700;color:var(--ancla);font-variant-numeric:tabular-nums;}
|
||||||
|
.tdesc-tot .per{font-size:11px;color:var(--tinta-suave);text-transform:uppercase;letter-spacing:.04em;}
|
||||||
|
.tdesc-tot .fl{color:var(--tinta-suave);font-size:15px;}
|
||||||
|
.tdesc-tot .delta{margin-left:auto;font-size:16px;font-weight:700;font-variant-numeric:tabular-nums;}
|
||||||
|
.tdesc-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:16px;}
|
||||||
|
.tdesc-card .lbl{font-size:12px;font-weight:700;color:var(--profundo);margin-bottom:3px;line-height:1.25;}
|
||||||
|
.tdesc-card .amt{font-size:21px;font-weight:700;font-variant-numeric:tabular-nums;line-height:1.1;margin-bottom:7px;}
|
||||||
|
.tdesc-card .det{font-size:11px;color:var(--tinta-suave);margin-top:6px;font-variant-numeric:tabular-nums;}
|
||||||
|
.tdesc-up{color:var(--gana);} .tdesc-down{color:var(--pierde);}
|
||||||
|
/* panels grid */
|
||||||
|
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:18px;}
|
||||||
|
.grid3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:18px;align-items:stretch;}
|
||||||
|
@media(max-width:1180px){.grid3{grid-template-columns:1fr 1fr;}}
|
||||||
|
@media(max-width:820px){.grid2,.grid3{grid-template-columns:1fr;}}
|
||||||
|
/* Indicadores (1/3) + tabla de detalle (2/3) lado a lado — pensado para la 1:1 con el ejecutivo:
|
||||||
|
clic en un indicador de la izquierda y la tabla de la derecha reacciona sin perderla de vista. */
|
||||||
|
.split23{display:grid;grid-template-columns:1fr 2fr;gap:18px;align-items:start;}
|
||||||
|
.split23>.split23-ind .panel{margin-bottom:14px;}
|
||||||
|
@media(max-width:980px){.split23{grid-template-columns:1fr;}}
|
||||||
|
/* Separador de sección: título corto entre bloques de paneles de distinta naturaleza (p.ej.
|
||||||
|
la tabla de detalle vs. los paneles de diagnóstico secundarios que siguen). */
|
||||||
|
.sec-div{margin:28px 0 18px;padding-top:16px;border-top:2px solid var(--linea);}
|
||||||
|
.sec-div span{font-size:13px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--marca);}
|
||||||
|
.panel{background:var(--panel);border:1px solid var(--linea);border-radius:10px;padding:16px 18px;margin-bottom:18px;box-shadow:0 1px 2px rgba(1,32,91,.05),0 2px 8px rgba(1,32,91,.04);}
|
||||||
|
.panel h3{font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--profundo);margin:0 0 4px;}
|
||||||
|
.panel .hint{font-size:11px;color:var(--tinta-suave);margin:0 0 12px;}
|
||||||
|
/* bar rows */
|
||||||
|
.row{display:grid;grid-template-columns:1fr 90px 34px;align-items:center;gap:9px;padding:5px 4px;border-radius:5px;cursor:pointer;transition:background .1s,opacity .12s;}
|
||||||
|
.row:hover{background:var(--gana-soft);}
|
||||||
|
.row.active{background:var(--gana-soft);}
|
||||||
|
.row.dim{opacity:.34;}
|
||||||
|
.row.static{cursor:default;} .row.static:hover{background:none;}
|
||||||
|
.row .bl{display:flex;align-items:center;gap:8px;min-width:0;}
|
||||||
|
.row .nm{font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||||
|
.row .track{position:absolute;inset:0;background:var(--gana-soft);border-radius:3px;}
|
||||||
|
.row .barwrap{position:relative;height:20px;border-radius:3px;background:#eef2f5;overflow:hidden;grid-column:1;display:none;}
|
||||||
|
.bar-cell{position:relative;height:9px;background:#edf1f5;border-radius:3px;overflow:hidden;flex:1;}
|
||||||
|
.bar-fill{position:absolute;left:0;top:0;height:100%;border-radius:3px;background:var(--marca);}
|
||||||
|
.bar-fill.pierde{background:var(--pierde);}
|
||||||
|
.bar-fill.alerta{background:var(--alerta);}
|
||||||
|
.row .v{font-family:var(--mono);font-size:11.5px;text-align:right;font-variant-numeric:tabular-nums;}
|
||||||
|
.row .c{font-family:var(--mono);font-size:10.5px;text-align:right;color:var(--tinta-suave);}
|
||||||
|
.row.dual{grid-template-columns:1fr 78px 40px 76px;}
|
||||||
|
|
||||||
|
/* Matriz calidad x movimiento (Tubería de Ventas) */
|
||||||
|
.mtz{display:grid;grid-template-columns:1fr 84px 84px;gap:3px;align-items:stretch;}
|
||||||
|
.mtz-h{font-size:11.5px;font-weight:700;text-transform:uppercase;letter-spacing:.04em;color:var(--profundo);text-align:center;padding:0 0 4px;}
|
||||||
|
.mtz-h.alerta{color:var(--pierde);font-weight:700;}
|
||||||
|
.mtz-r{font-size:12px;display:flex;align-items:center;gap:6px;padding:6px 2px;}
|
||||||
|
.mtz-r.tot{font-weight:700;color:var(--tinta-suave);font-size:11px;border-top:1px solid var(--linea);}
|
||||||
|
.mtz-c{background:#f4f7fa;border:1px solid transparent;border-radius:6px;padding:5px 4px;text-align:center;cursor:pointer;display:flex;flex-direction:column;gap:1px;transition:background .1s,border-color .1s;}
|
||||||
|
.mtz-c:hover{background:var(--gana-soft);}
|
||||||
|
.mtz-c.active{border-color:var(--marca);background:var(--palido);}
|
||||||
|
.mtz-c.foco{background:#fbe9e6;}
|
||||||
|
.mtz-c.foco:hover{background:#f7dbd6;}
|
||||||
|
.mtz-c.tot{background:none;cursor:default;border-top:1px solid var(--linea);border-radius:0;}
|
||||||
|
.mtz-c.tot:hover{background:none;}
|
||||||
|
.mtz-c .n{font-family:var(--mono);font-size:14px;font-weight:700;color:var(--ancla);line-height:1.1;}
|
||||||
|
.mtz-c.foco .n{color:var(--pierde);}
|
||||||
|
.mtz-c .v{font-family:var(--mono);font-size:12px;font-weight:700;color:var(--profundo);}
|
||||||
|
|
||||||
|
/* Matriz de ejecutivos × dimensión conmutable */
|
||||||
|
.mze{display:grid;gap:3px;align-items:stretch;}
|
||||||
|
.mze-h{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;color:var(--profundo);text-align:center;padding:0 2px 5px;line-height:1.25;align-self:end;}
|
||||||
|
.mze-h.tot{font-weight:700;}
|
||||||
|
.mze-r{font-size:12px;display:flex;align-items:center;padding:6px 6px 6px 2px;cursor:pointer;border-radius:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||||
|
.mze-r:hover{background:var(--gana-soft);}
|
||||||
|
.mze-r.active{background:var(--palido);font-weight:700;}
|
||||||
|
.mze-r.tot{font-weight:700;color:var(--tinta-suave);font-size:11px;cursor:default;border-top:1px solid var(--linea);}
|
||||||
|
.mze-r.tot:hover{background:none;}
|
||||||
|
.mze-c{border:1px solid transparent;border-radius:5px;padding:4px 2px;text-align:center;cursor:pointer;display:flex;flex-direction:column;justify-content:center;gap:0;transition:border-color .1s;}
|
||||||
|
.mze-c:hover{border-color:var(--marca);}
|
||||||
|
.mze-c.active{border-color:var(--marca);box-shadow:inset 0 0 0 1px var(--marca);}
|
||||||
|
.mze-c.vacia{cursor:default;}
|
||||||
|
.mze-c.vacia:hover{border-color:transparent;}
|
||||||
|
.mze-c.tot{background:none !important;cursor:default;border-top:1px solid var(--linea);border-radius:0;}
|
||||||
|
.mze-c.tot:hover{border-color:transparent;}
|
||||||
|
.mze-c .n{font-family:var(--mono);font-size:13px;font-weight:700;color:var(--ancla);line-height:1.15;}
|
||||||
|
.mze-c .n.vacio{color:#c8d2db;font-weight:400;}
|
||||||
|
.mze-c .v{font-family:var(--mono);font-size:11.5px;font-weight:700;color:var(--profundo);line-height:1.1;}
|
||||||
|
|
||||||
|
/* Rejilla de 3 columnas para los paneles de diagnóstico: más tablero a la vista sin scroll.
|
||||||
|
En columna angosta la fila se compacta (menos padding, barra más fina, cifras más chicas) y el
|
||||||
|
monto pierde peso visual — la lectura rápida es la cantidad, el monto es el respaldo. */
|
||||||
|
.grid3 .panel{padding:13px 14px;margin-bottom:0;display:flex;flex-direction:column;}
|
||||||
|
/* El último bloque de texto de un panel ("Fase más lenta", el promedio del termómetro) se ancla
|
||||||
|
abajo, para que las 3 tarjetas de una fila cierren a la misma altura sin dejar el pie flotando. */
|
||||||
|
.grid3 .panel>.hint:last-child{margin-top:auto;padding-top:8px;}
|
||||||
|
.grid3 .panel .hint{margin-bottom:9px;}
|
||||||
|
.grid3 .row{padding:3px 3px;gap:7px;}
|
||||||
|
.grid3 .row.dual{grid-template-columns:1fr 52px 30px 62px;}
|
||||||
|
.grid3 .row .nm{font-size:12px;}
|
||||||
|
.grid3 .row .v{font-size:11px;}
|
||||||
|
.grid3 .row .c{font-size:9.5px;}
|
||||||
|
.grid3 .bar-cell{height:7px;}
|
||||||
|
|
||||||
|
/* Control de período retrospectivo (mensual/semanal) de Ventas Resumen */
|
||||||
|
.vr-periodo{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px;}
|
||||||
|
.vr-periodo-lbl{font-size:12px;color:var(--tinta-suave);font-family:var(--mono);}
|
||||||
|
|
||||||
|
/* Dashboard de Ventas Resumen — cross-filter estilo Power BI */
|
||||||
|
/* Fila de barra: nombre completo en su propia línea (nunca se corta) + valores, barra debajo */
|
||||||
|
.dbar-row{padding:7px 4px;border-radius:6px;cursor:pointer;transition:background .1s,opacity .12s;}
|
||||||
|
.dbar-row:hover{background:var(--gana-soft);}
|
||||||
|
.dbar-row.active{background:var(--gana-soft);}
|
||||||
|
.dbar-row.dim{opacity:.34;}
|
||||||
|
.dbar-top{display:flex;justify-content:space-between;align-items:baseline;gap:10px;margin-bottom:4px;}
|
||||||
|
.dbar-top .nm{font-size:12.5px;color:var(--tinta);}
|
||||||
|
.dbar-top .vals{flex:none;font-family:var(--mono);font-size:11.5px;white-space:nowrap;}
|
||||||
|
.dbar-top .vals b{font-family:var(--sans);color:var(--ancla);}
|
||||||
|
.dbar-top .vals .c{color:var(--tinta-suave);margin-left:6px;}
|
||||||
|
.donut-arc{transition:opacity .12s;}
|
||||||
|
.donut-arc.dim{opacity:.3;}
|
||||||
|
.donut-leg-row{display:flex;align-items:center;gap:8px;padding:5px 4px;border-radius:5px;cursor:pointer;transition:background .1s,opacity .12s;}
|
||||||
|
.donut-leg-row:hover{background:var(--gana-soft);}
|
||||||
|
.donut-leg-row.active{background:var(--gana-soft);}
|
||||||
|
.donut-leg-row.dim{opacity:.34;}
|
||||||
|
.donut-leg-row .nm{flex:1;font-size:12.5px;}
|
||||||
|
.donut-leg-row .v{font-family:var(--mono);font-size:11.5px;width:34px;text-align:right;}
|
||||||
|
.donut-leg-row .c{font-family:var(--mono);font-size:10.5px;color:var(--tinta-suave);width:70px;text-align:right;}
|
||||||
|
.donut-dot{width:10px;height:10px;border-radius:50%;flex:none;}
|
||||||
|
/* callout */
|
||||||
|
.callout{border-radius:0 8px 8px 0;padding:14px 18px;font-size:13.5px;margin-bottom:14px;}
|
||||||
|
.callout.info{background:var(--palido);border-left:4px solid var(--marca);}
|
||||||
|
.callout.warn{background:var(--alerta-soft);border-left:4px solid var(--alerta);}
|
||||||
|
.callout.bad{background:var(--pierde-soft);border-left:4px solid var(--pierde);}
|
||||||
|
.callout b{color:var(--ancla);}
|
||||||
|
.callout.bad b{color:var(--pierde);}
|
||||||
|
/* table */
|
||||||
|
.tw{overflow-x:auto;border:1px solid var(--linea);border-radius:10px;background:var(--panel);box-shadow:0 1px 2px rgba(1,32,91,.05),0 2px 8px rgba(1,32,91,.04);}
|
||||||
|
.tw-title{display:flex;align-items:baseline;gap:10px;padding:14px 16px;border-bottom:1px solid var(--linea);}
|
||||||
|
.tw-title h3{font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--profundo);margin:0;}
|
||||||
|
.tw-title .tw-count{font-size:11px;color:var(--tinta-suave);font-family:var(--mono);}
|
||||||
|
/* Resalta la barra de título de una tabla puntual (p.ej. "Oportunidades para accionar esta
|
||||||
|
semana" en Previsión de Ventas) — franja de color a la izquierda y fondo tinte de alerta, para
|
||||||
|
que se distinga de las demás tablas de la página al primer vistazo. */
|
||||||
|
.tw-title.hi{background:var(--alerta-soft);border-left:4px solid var(--alerta);border-bottom-color:#ecdcb0;}
|
||||||
|
.tw-title.hi h3{color:#8a6414;}
|
||||||
|
/* <summary class="tw-title"> — secciones colapsables (ver página Actividades) */
|
||||||
|
summary.tw-title{list-style:none;}
|
||||||
|
summary.tw-title::-webkit-details-marker{display:none;}
|
||||||
|
summary.tw-title::marker{content:'';}
|
||||||
|
.tw-chevron{font-size:11px;color:var(--tinta-suave);transition:transform .12s;display:inline-block;}
|
||||||
|
details:not([open])>summary.tw-title .tw-chevron{transform:rotate(-90deg);}
|
||||||
|
.ts{max-height:460px;overflow-y:auto;}
|
||||||
|
/* Variante sin scroll horizontal: se usa donde la tabla declara sus anchos con <colgroup>.
|
||||||
|
El min-width global de `table` es lo que forzaba la barra lateral; aquí se anula. */
|
||||||
|
.tw.fit{overflow-x:hidden;}
|
||||||
|
/* Colchón fijo de seguridad: cuando SÍ aparece la barra vertical (más filas que `max-height`),
|
||||||
|
el ancho de una tabla `table-layout:fixed` a veces queda calculado por encima del disponible —
|
||||||
|
sin este margen, la última columna se recortaba unos 15px con `.tw.fit`, aunque las columnas
|
||||||
|
sumaran bien menos de 100%. Vale la pena perder una franja angosta en blanco cuando NO hay
|
||||||
|
barra a cambio de que nunca se corte cuando SÍ la hay. */
|
||||||
|
.tw.fit table.fix{width:calc(100% - 16px);}
|
||||||
|
/* Variante para layouts angostos (2/3 de ancho): sí hay scroll horizontal, pero la primera
|
||||||
|
columna (Cliente/Oportunidad) queda fija — el "quién" nunca se pierde al desplazarse a ver
|
||||||
|
Ejecutivo/MRR/Cierre. */
|
||||||
|
.tw.split table.fix thead th:first-child,.tw.split table.fix tbody td:first-child{position:sticky;left:0;z-index:2;background:var(--panel);box-shadow:2px 0 4px -2px rgba(1,32,91,.15);}
|
||||||
|
.tw.split table.fix thead th:first-child{z-index:3;background:var(--palido);}
|
||||||
|
.tw.split table.fix tbody tr:hover td:first-child{background:var(--gana-soft);}
|
||||||
|
/* Sin este piso, `width:100%` fuerza la tabla a caber en el 2/3 del layout dividido y
|
||||||
|
table-layout:fixed aplasta las columnas — la última (Agendar) quedaba cortada en vez de
|
||||||
|
simplemente empujar el scroll horizontal, que es el comportamiento que sí se busca acá. */
|
||||||
|
.tw.split table.fix{min-width:860px;}
|
||||||
|
table.fix{table-layout:fixed;min-width:0;}
|
||||||
|
table.fix thead th,table.fix tbody td{padding:6px 8px;}
|
||||||
|
table.fix td.elip{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||||
|
/* Cliente y oportunidad en una sola celda: el enlace arriba, el cliente como subíndice. */
|
||||||
|
td.dual-cel{white-space:normal;line-height:1.3;}
|
||||||
|
td.dual-cel .opp{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||||
|
td.dual-cel .sub{display:block;font-size:11.5px;color:var(--tinta);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||||
|
/* Indicador de actividad agendada (ver actIndicador() en tables.js) — pill chico junto al
|
||||||
|
nombre; "si" en verde discreto, "no" en rojo suave para que salte a la vista el hueco. */
|
||||||
|
td.dual-cel .act-ind{display:inline-block;margin-top:2px;font-size:10px;font-weight:700;padding:1px 5px;border-radius:8px;}
|
||||||
|
td.dual-cel .act-ind.si{background:var(--gana-soft);color:var(--profundo);}
|
||||||
|
td.dual-cel .act-ind.no{background:var(--pierde-soft);color:var(--pierde);}
|
||||||
|
/* Filas de grupo colapsable en tablePipe (ver `groupKey`) — encabezado clicleable con chevron;
|
||||||
|
arranca colapsado, clic para desplegar las filas de ese grupo. */
|
||||||
|
tr.grp-hdr{cursor:pointer;background:var(--palido);}
|
||||||
|
tr.grp-hdr:hover{background:#c3e0f2;}
|
||||||
|
tr.grp-hdr td{padding:8px 12px;font-size:12px;color:var(--profundo);border-bottom:1px solid var(--linea);}
|
||||||
|
.grp-chev{display:inline-block;width:12px;color:var(--marca);}
|
||||||
|
/* Plan de cierre como insignia de una letra — el nombre completo va en el title. */
|
||||||
|
.plan-b{display:inline-block;width:19px;height:19px;line-height:19px;text-align:center;border-radius:5px;font-size:11px;font-weight:700;background:var(--gris);color:var(--tinta-suave);}
|
||||||
|
.plan-b.pA{background:#d8ece0;color:#2f6b4f;}
|
||||||
|
.plan-b.pB{background:var(--gana-soft);color:var(--profundo);}
|
||||||
|
.plan-b.pC{background:var(--alerta-soft);color:#8a6414;}
|
||||||
|
.plan-b.pD{background:#f7ddd8;color:#9c3a2c;}
|
||||||
|
tbody td.num.venc{color:var(--pierde);font-weight:700;}
|
||||||
|
table{width:100%;border-collapse:collapse;font-size:12.5px;min-width:760px;}
|
||||||
|
/* Encabezado en azul pálido de marca con texto azul profundo: el gris sobre gris de antes tenía muy
|
||||||
|
poco contraste y la fila de títulos se perdía entre los datos. */
|
||||||
|
thead th{position:sticky;top:0;background:var(--palido);text-align:left;font-size:10px;letter-spacing:.04em;text-transform:uppercase;color:var(--profundo);font-weight:700;padding:9px 12px;border-bottom:2px solid var(--marca);white-space:nowrap;}
|
||||||
|
thead th.sortable{cursor:pointer;user-select:none;}
|
||||||
|
thead th.sortable:hover{background:#bfe1f2;}
|
||||||
|
thead th.on{color:var(--ancla);}
|
||||||
|
thead th .so{margin-left:5px;font-size:11px;opacity:.4;}
|
||||||
|
thead th.sortable:hover .so{opacity:.85;}
|
||||||
|
thead th.on .so{opacity:1;color:var(--marca);font-size:12px;}
|
||||||
|
/* El encabezado de una columna numérica se alinea con sus valores (a la derecha). Antes heredaba
|
||||||
|
text-align:left mientras los valores iban a la derecha: por eso se veían desalineadas. */
|
||||||
|
thead th.num{text-align:right;}
|
||||||
|
/* Líneas divisorias de columna — hacen legible una tabla ancha sin tener que seguir la fila con el dedo. */
|
||||||
|
thead th,tbody td{border-right:1px solid var(--linea);}
|
||||||
|
thead th:last-child,tbody td:last-child{border-right:none;}
|
||||||
|
tbody td{padding:7px 12px;border-bottom:1px solid var(--linea);white-space:nowrap;}
|
||||||
|
tbody td.num{text-align:right;font-variant-numeric:tabular-nums;}
|
||||||
|
tbody td.wrap{white-space:normal;min-width:220px;max-width:340px;font-size:11.5px;color:var(--tinta-suave);}
|
||||||
|
tbody td.wrap-p{white-space:normal;max-width:200px;}
|
||||||
|
tbody tr:hover{background:var(--gana-soft);}
|
||||||
|
tbody tr:last-child td{border-bottom:none;}
|
||||||
|
a.opp{color:var(--marca);text-decoration:none;font-weight:700;}
|
||||||
|
a.opp:hover{text-decoration:underline;}
|
||||||
|
.pill{display:inline-block;font-size:10.5px;padding:2px 8px;border-radius:10px;font-weight:700;}
|
||||||
|
.pill.nuevo{background:var(--gana-soft);color:var(--profundo);}
|
||||||
|
.pill.cartera{background:var(--alerta-soft);color:#8a6414;}
|
||||||
|
.seg-tabs{display:inline-flex;flex-wrap:wrap;border:1px solid var(--linea);border-radius:7px;overflow:hidden;}
|
||||||
|
.seg-tabs button{font-family:var(--sans);font-size:12.5px;padding:6px 14px;border:0;background:#fff;color:var(--tinta-suave);cursor:pointer;}
|
||||||
|
.seg-tabs button.on{background:var(--marca);color:#fff;font-weight:700;}
|
||||||
|
.soon-box{text-align:center;padding:80px 20px;color:var(--tinta-suave);}
|
||||||
|
.soon-box .big{font-size:44px;margin-bottom:12px;}
|
||||||
|
.soon-box h2{color:var(--ancla);font-size:22px;margin:0 0 8px;}
|
||||||
|
.rep-btn{font-family:var(--sans);font-size:13px;padding:8px 16px;border:1px solid var(--marca);border-radius:6px;background:#fff;color:var(--marca);cursor:pointer;font-weight:700;}
|
||||||
|
.rep-btn:hover{background:var(--gana-soft);}
|
||||||
|
|
||||||
|
/* Botones "agendar" por oportunidad (tabla de tubería) — patrón traído de «Gestión de Cuentas
|
||||||
|
Alfa»: abren Dynamics con una actividad nueva ya referida a esa oportunidad. Compactos a
|
||||||
|
propósito: la tabla ya lleva 13 columnas y esto no puede costarle ancho a los datos. */
|
||||||
|
.acc-grp{display:inline-flex;gap:3px;}
|
||||||
|
.acc-b{display:inline-flex;align-items:center;justify-content:center;width:19px;height:19px;
|
||||||
|
border:1px solid var(--linea);border-radius:4px;background:#fff;color:var(--marca);
|
||||||
|
font-size:10.5px;line-height:1;text-decoration:none;cursor:pointer;transition:background .12s,border-color .12s;}
|
||||||
|
.acc-b:hover{background:var(--marca);border-color:var(--marca);color:#fff;}
|
||||||
|
|
||||||
|
/* Tira compacta de notas de Previsión — reemplaza tres callouts apilados por uno de varias
|
||||||
|
líneas cortas. Mismo contenido, un tercio del alto. */
|
||||||
|
.callout.nota-tira{display:flex;flex-direction:column;gap:5px;font-size:12px;line-height:1.45;}
|
||||||
|
/* Insignia de bloqueo en la tabla de accionables (Previsión) */
|
||||||
|
.blq-pill{display:inline-block;padding:2px 7px;border-radius:10px;font-size:10.5px;font-weight:700;
|
||||||
|
background:var(--profundo-soft);color:var(--profundo);white-space:nowrap;cursor:help;}
|
||||||
|
.blq-pill.pierde{background:var(--pierde-soft);color:var(--pierde);}
|
||||||
|
.blq-pill.alerta{background:var(--alerta-soft);color:var(--alerta);}
|
||||||
|
|
||||||
|
/* ---- Página Agenda (pages/agenda.js) ----
|
||||||
|
Calendario de actividades planificadas. Patrón traído de «Gestión de Cuentas Alfa»
|
||||||
|
(Informe v2/agenda.html), reescrito sobre las variables de marca de este informe. */
|
||||||
|
.ag-f-lbl{display:block;font-size:10.5px;text-transform:uppercase;letter-spacing:.05em;color:var(--tinta-suave);margin-bottom:6px;}
|
||||||
|
.ag-tipos{display:flex;gap:14px;flex-wrap:wrap;}
|
||||||
|
.ag-tipo{display:inline-flex;align-items:center;gap:5px;font-size:12.5px;cursor:pointer;}
|
||||||
|
.ag-toolbar{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin-bottom:14px;}
|
||||||
|
.ag-nav{display:flex;align-items:center;gap:8px;}
|
||||||
|
.ag-nav-b{font-family:var(--sans);font-size:12.5px;padding:5px 11px;border:1px solid var(--linea);
|
||||||
|
border-radius:6px;background:#fff;color:var(--tinta);cursor:pointer;}
|
||||||
|
.ag-nav-b:hover{border-color:var(--marca);color:var(--marca);}
|
||||||
|
.ag-nav-lbl{font-size:13px;font-weight:700;color:var(--profundo);min-width:180px;text-align:center;}
|
||||||
|
|
||||||
|
.ag-week{display:grid;grid-template-columns:repeat(7,1fr);gap:10px;align-items:start;}
|
||||||
|
@media(max-width:1180px){.ag-week{grid-template-columns:repeat(4,1fr);}}
|
||||||
|
@media(max-width:820px){.ag-week{grid-template-columns:repeat(2,1fr);}}
|
||||||
|
.ag-day{background:var(--panel);border:1px solid var(--linea);border-radius:10px;padding:9px 9px 10px;
|
||||||
|
min-height:120px;display:flex;flex-direction:column;gap:6px;}
|
||||||
|
.ag-day.hoy{border-color:var(--marca);box-shadow:0 0 0 1px var(--marca) inset;}
|
||||||
|
.ag-day-h{display:flex;justify-content:space-between;font-size:10.5px;text-transform:uppercase;
|
||||||
|
letter-spacing:.04em;color:var(--tinta-suave);font-weight:700;margin-bottom:2px;}
|
||||||
|
.ag-vacio{font-size:11px;color:var(--tinta-suave);}
|
||||||
|
|
||||||
|
.ag-item{display:block;border-radius:6px;padding:6px 8px;text-decoration:none;
|
||||||
|
border-left:3px solid var(--marca);background:var(--gana-soft);color:var(--tinta);}
|
||||||
|
.ag-item:hover{filter:brightness(.97);}
|
||||||
|
.ag-item-t{display:block;font-size:11.5px;font-weight:700;line-height:1.3;}
|
||||||
|
.ag-item-s{display:block;font-size:10.5px;color:var(--tinta-suave);margin-top:2px;}
|
||||||
|
.ag-item.t-cita{border-left-color:var(--alerta);background:var(--alerta-soft);}
|
||||||
|
.ag-item.t-llamada{border-left-color:var(--profundo);background:var(--profundo-soft);}
|
||||||
|
.ag-item.venc{border-left-color:var(--pierde);background:var(--pierde-soft);}
|
||||||
|
.ag-item.hecha{opacity:.55;}
|
||||||
|
.ag-lista{display:flex;flex-direction:column;gap:7px;}
|
||||||
|
|
||||||
|
.ag-month{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;}
|
||||||
|
.ag-m-h{font-size:10.5px;text-transform:uppercase;letter-spacing:.04em;color:var(--tinta-suave);
|
||||||
|
font-weight:700;text-align:center;padding-bottom:4px;}
|
||||||
|
.ag-m-d{position:relative;background:var(--panel);border:1px solid var(--linea);border-radius:8px;
|
||||||
|
min-height:56px;padding:6px 7px;cursor:pointer;}
|
||||||
|
.ag-m-d:hover{border-color:var(--marca);}
|
||||||
|
.ag-m-d.otro{opacity:.42;}
|
||||||
|
.ag-m-d.hoy{border-color:var(--marca);box-shadow:0 0 0 1px var(--marca) inset;}
|
||||||
|
.ag-m-d.sel{background:var(--gana-soft);border-color:var(--marca);}
|
||||||
|
.ag-m-num{font-size:11.5px;font-family:var(--mono);color:var(--tinta-suave);}
|
||||||
|
.ag-m-badge{position:absolute;right:6px;bottom:6px;min-width:18px;height:18px;border-radius:9px;
|
||||||
|
background:var(--marca);color:#fff;font-size:10.5px;font-weight:700;display:inline-flex;
|
||||||
|
align-items:center;justify-content:center;padding:0 5px;}
|
||||||
|
.ag-m-badge.venc{background:var(--pierde);}
|
||||||
|
.ag-lista.scroll{max-height:560px;overflow-y:auto;padding-right:5px;}
|
||||||
|
|
||||||
|
/* ---- Nuevas Oportunidades (pages/nuevas.js) ----
|
||||||
|
Barras apiladas de cohorte + insignias de estado. La matriz de calor reusa las clases .mze
|
||||||
|
de la matriz de ejecutivos; solo cambia el color de fondo, que lo calcula cohHeat(). */
|
||||||
|
.coh-leyenda{display:flex;gap:16px;margin-bottom:12px;}
|
||||||
|
.coh-leg{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;color:var(--tinta-suave);}
|
||||||
|
.coh-leg i{width:11px;height:11px;border-radius:3px;display:inline-block;}
|
||||||
|
.coh-fila{display:grid;grid-template-columns:minmax(96px,120px) 1fr 46px;align-items:center;gap:10px;padding:5px 0;}
|
||||||
|
.coh-mes{font-size:12px;color:var(--tinta);}
|
||||||
|
.coh-tot{font-family:var(--mono);font-size:11.5px;color:var(--tinta-suave);text-align:right;}
|
||||||
|
.coh-barra{display:flex;height:26px;border-radius:5px;overflow:hidden;background:var(--gris);}
|
||||||
|
.coh-seg{display:flex;align-items:center;justify-content:center;color:#fff;font-size:10.5px;
|
||||||
|
font-weight:700;cursor:pointer;transition:filter .12s;white-space:nowrap;overflow:hidden;}
|
||||||
|
.coh-seg:hover{filter:brightness(1.12);}
|
||||||
|
.coh-seg.sel{outline:2px solid var(--ancla);outline-offset:-2px;}
|
||||||
|
.coh-vacio{font-size:11px;color:var(--tinta-suave);padding-left:8px;align-self:center;}
|
||||||
|
.coh-pill{display:inline-block;padding:2px 8px;border-radius:10px;font-size:10.5px;font-weight:700;white-space:nowrap;}
|
||||||
|
.coh-pill.g{background:var(--gana-soft);color:var(--gana);}
|
||||||
|
.coh-pill.p{background:var(--pierde-soft);color:var(--pierde);}
|
||||||
|
.coh-pill.a{background:var(--gris);color:var(--tinta-suave);}
|
||||||
45
public/assets/css/layout.css
Normal file
45
public/assets/css/layout.css
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
.app{display:flex;min-height:100vh;}
|
||||||
|
/* SIDEBAR */
|
||||||
|
.side{width:230px;background:var(--ancla);color:#fff;flex-shrink:0;display:flex;flex-direction:column;position:sticky;top:0;height:100vh;}
|
||||||
|
.side-logo{padding:22px 20px 16px;border-bottom:1px solid rgba(255,255,255,.12);}
|
||||||
|
.side-logo img{height:30px;width:auto;display:block;}
|
||||||
|
.side-logo .sub{font-size:10.5px;letter-spacing:.14em;text-transform:uppercase;color:var(--palido);margin-top:8px;opacity:.85;}
|
||||||
|
.nav{padding:10px 0;overflow-y:auto;flex:1;}
|
||||||
|
/* Encabezado de grupo de la navegación — con 16 páginas una lista plana deja de ser escaneable. */
|
||||||
|
.nav-grupo{font-size:10px;text-transform:uppercase;letter-spacing:.09em;color:#7fa3c4;
|
||||||
|
padding:14px 20px 5px;font-weight:700;user-select:none;}
|
||||||
|
.nav-grupo:first-child{padding-top:6px;}
|
||||||
|
.nav-item{display:flex;align-items:center;gap:10px;padding:8px 20px;font-size:13px;color:#cfe0ef;cursor:pointer;border-left:3px solid transparent;user-select:none;}
|
||||||
|
.nav-item:hover{background:rgba(255,255,255,.06);color:#fff;}
|
||||||
|
.nav-item.active{background:rgba(30,113,184,.28);border-left-color:var(--marca);color:#fff;font-weight:700;}
|
||||||
|
.nav-item.soon{color:#6f8399;cursor:not-allowed;}
|
||||||
|
.nav-item.soon:hover{background:none;}
|
||||||
|
.nav-item .ico{width:16px;text-align:center;font-size:14px;}
|
||||||
|
.nav-item .tag{margin-left:auto;font-size:8.5px;letter-spacing:.05em;background:rgba(255,255,255,.12);color:#9db4c9;padding:2px 6px;border-radius:8px;text-transform:uppercase;}
|
||||||
|
.side-foot{padding:12px 20px;border-top:1px solid rgba(255,255,255,.12);font-family:var(--mono);font-size:10px;color:#7f95aa;}
|
||||||
|
.side-foot-aviso{margin-top:6px;color:var(--alerta);font-weight:600;}
|
||||||
|
/* MAIN */
|
||||||
|
.main{flex:1;min-width:0;display:flex;flex-direction:column;}
|
||||||
|
.topbar{background:var(--panel);border-bottom:1px solid var(--linea);padding:14px 28px;display:flex;align-items:center;gap:20px;flex-wrap:wrap;position:sticky;top:0;z-index:10;}
|
||||||
|
.topbar h1{font-size:19px;font-weight:700;margin:0;color:var(--ancla);flex:1;min-width:180px;}
|
||||||
|
.content{padding:26px 28px 80px;}
|
||||||
|
.page{display:none;}
|
||||||
|
.page.active{display:block;}
|
||||||
|
.hamburger{display:none;background:none;border:1px solid var(--linea);border-radius:6px;padding:6px 10px;font-size:18px;cursor:pointer;color:var(--ancla);line-height:1;}
|
||||||
|
.backdrop{display:none;position:fixed;inset:0;background:rgba(1,32,91,.35);z-index:19;}
|
||||||
|
@media(max-width:820px){
|
||||||
|
.side{position:fixed;top:0;left:0;z-index:20;transform:translateX(-100%);transition:transform .2s ease;}
|
||||||
|
.side.open{transform:translateX(0);}
|
||||||
|
.backdrop.open{display:block;}
|
||||||
|
.hamburger{display:inline-block;}
|
||||||
|
/* El colapso de .grid2/.grid3 se movió a components.css: esa hoja carga después y su regla
|
||||||
|
base gana por orden, así que la media query de aquí nunca aplicaba. */
|
||||||
|
.content{padding:20px 16px 80px;}
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce){.side{transition:none;}}
|
||||||
|
@media print{
|
||||||
|
body.rep-print .side,body.rep-print .topbar,body.rep-print .backdrop,body.rep-print .content,body.rep-print #mapModalBd,body.rep-print #mapModal{display:none !important;}
|
||||||
|
body.rep-print #repModalBd{display:none !important;}
|
||||||
|
body.rep-print #repModal{position:static !important;inset:auto !important;box-shadow:none !important;border-radius:0 !important;padding:0 !important;max-height:none !important;overflow:visible !important;}
|
||||||
|
body.rep-print .rep-actions{display:none !important;}
|
||||||
|
}
|
||||||
BIN
public/assets/fonts/UbuntuSans-Bold.ttf
Normal file
BIN
public/assets/fonts/UbuntuSans-Bold.ttf
Normal file
Binary file not shown.
BIN
public/assets/fonts/UbuntuSans-Regular.ttf
Normal file
BIN
public/assets/fonts/UbuntuSans-Regular.ttf
Normal file
Binary file not shown.
BIN
public/assets/img/logo-alfa-blanco.png
Normal file
BIN
public/assets/img/logo-alfa-blanco.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Loading…
Reference in a new issue