feat: PWA instalable, cambio de contraseña y dashboards por rol
- POST /api/auth/cambiar-password (bcrypt 12, política ≥8+1 número) + modal en las 6 apps con auth - PWA: manifest + íconos de marca en las 7 apps (sin service worker a propósito, documentado); instalable en celular - Dashboards: 'Mi tablero' para vendedor (sus KPIs y funnel) y sección Equipo para coordinador/corporativo/admin - mi-dia: equipo.porVendedor gana leadsNuevosSemana - Tests: api 271, cotizador 88, alta 88, cobranza 81, agente-ia 19, dashboards 15, mi-dia 11, landing 4
This commit is contained in:
@@ -1,255 +1,49 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Cell,
|
||||
Funnel,
|
||||
FunnelChart,
|
||||
LabelList,
|
||||
Legend,
|
||||
Pie,
|
||||
PieChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts'
|
||||
import KpiCard from '../components/KpiCard'
|
||||
import {
|
||||
datosCobranza,
|
||||
datosFunnel,
|
||||
datosPipeline,
|
||||
formatoMoneda,
|
||||
formatoPorcentaje,
|
||||
unidadesApiladas,
|
||||
unidadesEnEtapa,
|
||||
type ResumenReportes,
|
||||
} from '../lib/reportes'
|
||||
import { fetchResumen } from '../services/reportes'
|
||||
import { useState } from 'react'
|
||||
import MiTablero from '../components/MiTablero'
|
||||
import TableroGeneral from '../components/TableroGeneral'
|
||||
import { esRolConEquipo } from '../lib/mi-tablero'
|
||||
import { getSesion } from '../services/auth'
|
||||
|
||||
// Paleta StudioBlank: acento verde + neutros (sin gradientes ni sombras)
|
||||
const COLORES_STATUS: Record<string, string> = {
|
||||
DISPONIBLE: '#1B4332',
|
||||
APARTADO: '#b45309',
|
||||
VENDIDO: '#525252',
|
||||
BLOQUEADO: '#b91c1c',
|
||||
OTROS: '#d4d4d4',
|
||||
}
|
||||
const COLORES_FUNNEL = ['#a3a3a3', '#737373', '#52796f', '#1B4332']
|
||||
const COLORES_COBRANZA = ['#1B4332', '#b45309']
|
||||
type Vista = 'mia' | 'general'
|
||||
|
||||
const VISTAS: { id: Vista; etiqueta: string }[] = [
|
||||
{ id: 'mia', etiqueta: 'Mi tablero' },
|
||||
{ id: 'general', etiqueta: 'General' },
|
||||
]
|
||||
|
||||
/**
|
||||
* Tableros con vista por rol: el vendedor entra a "Mi tablero" (sus KPIs y el
|
||||
* funnel de sus leads); coordinador/corporativo/admin entran a "General" con
|
||||
* la sección Equipo. El toggle permite cambiar de vista en cualquier momento.
|
||||
*/
|
||||
export default function DashboardPage() {
|
||||
const rol = getSesion()?.usuario.rol ?? 'vendedor'
|
||||
const conEquipo = esRolConEquipo(rol)
|
||||
const [vista, setVista] = useState<Vista>(conEquipo ? 'general' : 'mia')
|
||||
|
||||
function EstadoVacio({ mensaje }: { mensaje: string }) {
|
||||
return (
|
||||
<div className="flex h-64 items-center justify-center border border-dashed border-neutral-300">
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-neutral-400">{mensaje}</p>
|
||||
<div>
|
||||
<div className="border-b border-neutral-200 bg-white">
|
||||
<div className="mx-auto flex max-w-6xl gap-2 px-4 py-3" role="tablist" aria-label="Vista del tablero">
|
||||
{VISTAS.map((v) => (
|
||||
<button
|
||||
key={v.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={vista === v.id}
|
||||
onClick={() => setVista(v.id)}
|
||||
className={
|
||||
vista === v.id
|
||||
? 'bg-accent px-5 py-2 text-xs font-bold uppercase tracking-widest text-white'
|
||||
: 'border border-neutral-300 px-5 py-2 text-xs font-bold uppercase tracking-widest text-neutral-500 transition-colors duration-150 hover:border-neutral-500'
|
||||
}
|
||||
>
|
||||
{v.etiqueta}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{vista === 'mia' ? <MiTablero /> : <TableroGeneral mostrarEquipo={conEquipo} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TituloSeccion({ children }: { children: string }) {
|
||||
return <h2 className="mb-4 text-xs font-bold uppercase tracking-widest text-neutral-500">{children}</h2>
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const [resumen, setResumen] = useState<ResumenReportes | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [cargando, setCargando] = useState(true)
|
||||
|
||||
const cargar = useCallback(async () => {
|
||||
setCargando(true)
|
||||
try {
|
||||
setResumen(await fetchResumen())
|
||||
setError(null)
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'No se pudo cargar el tablero')
|
||||
} finally {
|
||||
setCargando(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void cargar()
|
||||
}, [cargar])
|
||||
|
||||
const unidades = resumen ? unidadesApiladas(resumen) : []
|
||||
const funnel = resumen ? datosFunnel(resumen) : []
|
||||
const cobranza = resumen ? datosCobranza(resumen) : []
|
||||
const pipeline = resumen ? datosPipeline(resumen) : []
|
||||
const sinPipeline = pipeline.every((e) => e.valor === 0)
|
||||
const sinCobranza = resumen !== null && resumen.cobranza.planesAlCorriente + resumen.cobranza.planesConVencidos === 0
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-6xl px-4 py-8">
|
||||
<div className="mb-8 flex items-end justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-accent">FRASA Desarrollos</p>
|
||||
<h1 className="mt-2 text-3xl font-light text-neutral-900">Tablero comercial</h1>
|
||||
{resumen && (
|
||||
<p className="mt-1 text-xs text-neutral-400">
|
||||
Actualizado: {new Date(resumen.generadoEn).toLocaleString('es-MX')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void cargar()}
|
||||
disabled={cargando}
|
||||
className="border border-accent px-5 py-2 text-xs font-bold uppercase tracking-widest text-accent transition-colors duration-150 hover:bg-accent hover:text-white disabled:opacity-50"
|
||||
>
|
||||
{cargando ? 'Actualizando…' : 'Actualizar'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p role="alert" className="mb-8 border border-amber-700 px-4 py-3 text-xs font-bold uppercase tracking-widest text-amber-700">
|
||||
Sin datos del API — {error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!resumen && !error && cargando && <EstadoVacio mensaje="Cargando…" />}
|
||||
{!resumen && !error && !cargando && <EstadoVacio mensaje="Sin datos" />}
|
||||
|
||||
{resumen && (
|
||||
<>
|
||||
<section aria-label="Indicadores clave" className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<KpiCard
|
||||
titulo="Leads totales"
|
||||
valor={resumen.leads.total}
|
||||
detalle={`${resumen.leads.nuevosHoy} hoy · ${resumen.leads.nuevosSemana} esta semana`}
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Oportunidades activas"
|
||||
valor={resumen.oportunidades.activas}
|
||||
detalle={`${resumen.oportunidades.total} en total`}
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Conversión Aparto / Ganado"
|
||||
valor={`${formatoPorcentaje(resumen.oportunidades.tasaAparto)} / ${formatoPorcentaje(resumen.oportunidades.tasaGanado)}`}
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Unidades disponibles"
|
||||
valor={resumen.unidades.disponibles}
|
||||
detalle={`${resumen.unidades.total} en inventario`}
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Cartera vencida"
|
||||
valor={formatoMoneda(resumen.cobranza.montoVencido)}
|
||||
detalle={`${resumen.cobranza.pagosVencidos} pago(s) vencido(s)`}
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Planes activos"
|
||||
valor={resumen.cobranza.planes.activos}
|
||||
detalle={`${resumen.cobranza.planes.liquidados} liquidados · ${resumen.cobranza.planes.cancelados} cancelados`}
|
||||
/>
|
||||
<KpiCard titulo="Actividades abiertas" valor={resumen.actividadesAbiertas} />
|
||||
<KpiCard
|
||||
titulo="En notaría"
|
||||
valor={unidadesEnEtapa(resumen, 'Notaría')}
|
||||
detalle="unidades en etapa Notaría"
|
||||
/>
|
||||
<KpiCard
|
||||
titulo="Leads por contactar"
|
||||
valor={resumen.leads.porEstado['NUEVO'] ?? 0}
|
||||
detalle="en estado NUEVO"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section aria-label="Inventario por desarrollo" className="mt-12">
|
||||
<TituloSeccion>Unidades por desarrollo y status</TituloSeccion>
|
||||
{unidades.length === 0 ? (
|
||||
<EstadoVacio mensaje="Sin inventario" />
|
||||
) : (
|
||||
<div className="h-72">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={unidades} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="desarrollo" tick={{ fontSize: 11 }} />
|
||||
<YAxis allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||
<Tooltip />
|
||||
<Legend wrapperStyle={{ fontSize: 11 }} />
|
||||
{Object.keys(COLORES_STATUS).map((status) => (
|
||||
<Bar key={status} dataKey={status} stackId="unidades" fill={COLORES_STATUS[status]} />
|
||||
))}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section aria-label="Pipeline de ventas por etapa" className="mt-12">
|
||||
<TituloSeccion>Pipeline de ventas por etapa</TituloSeccion>
|
||||
{sinPipeline ? (
|
||||
<EstadoVacio mensaje="Sin unidades en el pipeline" />
|
||||
) : (
|
||||
<div className="h-80">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={pipeline} layout="vertical" margin={{ top: 8, right: 24, left: 24, bottom: 0 }}>
|
||||
<CartesianGrid strokeDasharray="3 3" horizontal={false} />
|
||||
<XAxis type="number" allowDecimals={false} tick={{ fontSize: 11 }} />
|
||||
<YAxis type="category" dataKey="etapa" width={90} tick={{ fontSize: 11 }} />
|
||||
<Tooltip />
|
||||
<Bar dataKey="valor" name="Unidades" fill="#1B4332" isAnimationActive={false} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="mt-12 grid gap-12 lg:grid-cols-2">
|
||||
<section aria-label="Embudo comercial">
|
||||
<TituloSeccion>Embudo: leads → oportunidades → ganado</TituloSeccion>
|
||||
{funnel.every((e) => e.valor === 0) ? (
|
||||
<EstadoVacio mensaje="Sin movimiento comercial" />
|
||||
) : (
|
||||
<div className="h-72">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<FunnelChart>
|
||||
<Tooltip />
|
||||
<Funnel dataKey="valor" data={funnel} nameKey="etapa" isAnimationActive={false}>
|
||||
{funnel.map((etapa, i) => (
|
||||
<Cell key={etapa.etapa} fill={COLORES_FUNNEL[i % COLORES_FUNNEL.length]} />
|
||||
))}
|
||||
<LabelList position="right" dataKey="etapa" stroke="none" fontSize={11} />
|
||||
<LabelList position="center" dataKey="valor" stroke="none" fill="#fff" fontSize={12} />
|
||||
</Funnel>
|
||||
</FunnelChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section aria-label="Estado de la cobranza">
|
||||
<TituloSeccion>Cobranza: al corriente vs vencidos</TituloSeccion>
|
||||
{sinCobranza ? (
|
||||
<EstadoVacio mensaje="Sin planes activos" />
|
||||
) : (
|
||||
<div className="h-72">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={cobranza}
|
||||
dataKey="valor"
|
||||
nameKey="nombre"
|
||||
innerRadius={60}
|
||||
outerRadius={90}
|
||||
isAnimationActive={false}
|
||||
label={({ name, value }) => `${name}: ${value}`}
|
||||
fontSize={11}
|
||||
>
|
||||
{cobranza.map((rebanada, i) => (
|
||||
<Cell key={rebanada.nombre} fill={COLORES_COBRANZA[i % COLORES_COBRANZA.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user