feat: automatizaciones ronda 2 + app de dashboards /dash
- Escalado: lead asignado sin contactar >48h genera actividad URGENTE al coordinador (LEAD_ESCALADO_HORAS, MONDAY_COORDINADOR_USER_ID) - Oportunidad en Aparto crea item en Apartado (fecha límite +7d); en Ganado crea la Venta; ambos con dedup - GET /api/reportes/resumen: leads, funnel, unidades por desarrollo, cobranza y actividades en una respuesta (cache 60s) - App dashboards (/dash): 8 KPIs + 3 gráficas Recharts, con auth - Landing: tarjeta Tableros; docs/AUTOMATIZACIONES-MONDAY.md con las recetas nativas para activar en la UI - Tests: api 158, dashboards 7, landing 5 — todo verde
This commit is contained in:
12
apps/dashboards/index.html
Normal file
12
apps/dashboards/index.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>FRASA Desarrollos — Tableros</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
4280
apps/dashboards/package-lock.json
generated
Normal file
4280
apps/dashboards/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
apps/dashboards/package.json
Normal file
28
apps/dashboards/package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "dashboards",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.3.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"recharts": "^2.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@types/react": "^19.0.2",
|
||||
"@types/react-dom": "^19.0.2",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^6.0.7",
|
||||
"vitest": "^2.1.8"
|
||||
}
|
||||
}
|
||||
38
apps/dashboards/src/components/AuthGate.tsx
Normal file
38
apps/dashboards/src/components/AuthGate.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { getSesion, logout, type Sesion } from '../services/auth'
|
||||
import LoginScreen from './LoginScreen'
|
||||
|
||||
/**
|
||||
* Gate de autenticación: sin sesión solo se ve el login; con sesión se ve la
|
||||
* app con una barra discreta "nombre · rol" y botón "Salir".
|
||||
*/
|
||||
export default function AuthGate({ children }: { children: ReactNode }) {
|
||||
const [sesion, setSesion] = useState<Sesion | null>(() => getSesion())
|
||||
|
||||
if (!sesion) {
|
||||
return <LoginScreen onLogin={() => setSesion(getSesion())} />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white text-neutral-900">
|
||||
<div className="border-b border-neutral-200">
|
||||
<div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-2">
|
||||
<span className="text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
{sesion.usuario.nombre} · {sesion.usuario.rol}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
logout()
|
||||
setSesion(null)
|
||||
}}
|
||||
className="text-xs font-bold uppercase tracking-widest text-accent transition-colors duration-150 hover:text-accent-hover"
|
||||
>
|
||||
Salir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
11
apps/dashboards/src/components/KpiCard.tsx
Normal file
11
apps/dashboards/src/components/KpiCard.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export default function KpiCard({ titulo, valor, detalle }: { titulo: string; valor: ReactNode; detalle?: string }) {
|
||||
return (
|
||||
<div className="border border-neutral-200 bg-white p-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest text-neutral-500">{titulo}</p>
|
||||
<p className="mt-2 text-3xl font-light text-neutral-900">{valor}</p>
|
||||
{detalle && <p className="mt-2 text-xs text-neutral-500">{detalle}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
88
apps/dashboards/src/components/LoginScreen.tsx
Normal file
88
apps/dashboards/src/components/LoginScreen.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { login, ErrorLogin, type UsuarioSesion } from '../services/auth'
|
||||
|
||||
/** Pantalla de login StudioBlank: marca FRASA, usuario + contraseña, Enter envía */
|
||||
export default function LoginScreen({ onLogin }: { onLogin: (usuario: UsuarioSesion) => void }) {
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [cargando, setCargando] = useState(false)
|
||||
|
||||
async function enviar(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
setError(null)
|
||||
setCargando(true)
|
||||
try {
|
||||
onLogin(await login(username, password))
|
||||
} catch (err) {
|
||||
setError(err instanceof ErrorLogin ? err.message : 'Usuario o contraseña incorrectos')
|
||||
} finally {
|
||||
setCargando(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-white px-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="mb-10 text-center">
|
||||
<p className="text-lg font-bold tracking-widest">FRASA</p>
|
||||
<p className="mt-2 text-xs font-bold uppercase tracking-widest text-neutral-500">
|
||||
Acceso al ecosistema
|
||||
</p>
|
||||
</div>
|
||||
<form onSubmit={enviar} className="space-y-6">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="login-usuario"
|
||||
className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500"
|
||||
>
|
||||
Usuario
|
||||
</label>
|
||||
<input
|
||||
id="login-usuario"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
required
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="login-password"
|
||||
className="mb-2 block text-xs font-bold uppercase tracking-widest text-neutral-500"
|
||||
>
|
||||
Contraseña
|
||||
</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="w-full border border-neutral-300 px-4 py-3 text-sm focus:border-accent focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p
|
||||
role="alert"
|
||||
className="border border-red-700 px-4 py-3 text-xs font-bold uppercase tracking-widest text-red-700"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={cargando}
|
||||
className="w-full bg-accent px-5 py-3 text-xs font-bold uppercase tracking-widest text-white transition-colors duration-150 hover:bg-accent-hover disabled:opacity-50"
|
||||
>
|
||||
{cargando ? 'Entrando…' : 'Entrar'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
23
apps/dashboards/src/index.css
Normal file
23
apps/dashboards/src/index.css
Normal file
@@ -0,0 +1,23 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
--color-accent: #1B4332;
|
||||
--radius-sm: 0;
|
||||
--radius-md: 0;
|
||||
--radius-lg: 0;
|
||||
--radius-xl: 0;
|
||||
--radius-2xl: 0;
|
||||
--radius-3xl: 0;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-white text-neutral-900 antialiased;
|
||||
}
|
||||
|
||||
*:focus-visible {
|
||||
outline: 2px solid #1B4332;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
91
apps/dashboards/src/lib/reportes.test.ts
Normal file
91
apps/dashboards/src/lib/reportes.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
datosCobranza,
|
||||
datosFunnel,
|
||||
formatoMoneda,
|
||||
formatoPorcentaje,
|
||||
unidadesApiladas,
|
||||
type ResumenReportes,
|
||||
} from './reportes'
|
||||
|
||||
function resumen(overrides: Partial<ResumenReportes> = {}): ResumenReportes {
|
||||
return {
|
||||
generadoEn: '2026-08-22T12:00:00.000Z',
|
||||
leads: { total: 40, nuevosHoy: 3, nuevosSemana: 12, porEstado: {}, porOrigen: {} },
|
||||
oportunidades: {
|
||||
total: 20,
|
||||
activas: 15,
|
||||
porEtapa: { Afluencia: 8, Cotizador: 5, Aparto: 4, Ganado: 2, Perdido: 1 },
|
||||
tasaAparto: 0.3,
|
||||
tasaGanado: 0.1,
|
||||
},
|
||||
unidades: {
|
||||
total: 5,
|
||||
disponibles: 2,
|
||||
porDesarrollo: [
|
||||
{ desarrollo: 'ATELIER', total: 3, porStatus: { DISPONIBLE: 1, VENDIDO: 2 } },
|
||||
{ desarrollo: 'SOLANA', total: 2, porStatus: { DISPONIBLE: 1, ESCRITURADO: 1 } },
|
||||
],
|
||||
},
|
||||
cobranza: {
|
||||
planes: { activos: 6, liquidados: 2, cancelados: 1 },
|
||||
planesAlCorriente: 4,
|
||||
planesConVencidos: 2,
|
||||
pagosVencidos: 3,
|
||||
montoVencido: 125000,
|
||||
},
|
||||
actividadesAbiertas: 7,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('unidadesApiladas', () => {
|
||||
it('mapea desarrollo × status con columnas fijas y agrupa lo desconocido en OTROS', () => {
|
||||
expect(unidadesApiladas(resumen())).toEqual([
|
||||
{ desarrollo: 'ATELIER', DISPONIBLE: 1, APARTADO: 0, VENDIDO: 2, BLOQUEADO: 0, OTROS: 0 },
|
||||
{ desarrollo: 'SOLANA', DISPONIBLE: 1, APARTADO: 0, VENDIDO: 0, BLOQUEADO: 0, OTROS: 1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('con inventario vacío devuelve arreglo vacío', () => {
|
||||
expect(unidadesApiladas(resumen({ unidades: { total: 0, disponibles: 0, porDesarrollo: [] } }))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('datosFunnel', () => {
|
||||
it('ordena Leads → Oportunidades → Aparto o más → Ganado sin subir', () => {
|
||||
const funnel = datosFunnel(resumen())
|
||||
expect(funnel.map((e) => e.etapa)).toEqual(['Leads', 'Oportunidades', 'Aparto o más', 'Ganado'])
|
||||
expect(funnel.map((e) => e.valor)).toEqual([40, 20, 6, 2]) // Aparto(4) + Ganado(2) acumulados
|
||||
const valores = funnel.map((e) => e.valor)
|
||||
for (let i = 1; i < valores.length; i++) expect(valores[i]!).toBeLessThanOrEqual(valores[i - 1]!)
|
||||
})
|
||||
|
||||
it('tolera etiquetas con otra capitalización', () => {
|
||||
const r = resumen()
|
||||
r.oportunidades.porEtapa = { aparto: 1, ' GANADO ': 3 }
|
||||
const funnel = datosFunnel(r)
|
||||
expect(funnel[2]?.valor).toBe(4)
|
||||
expect(funnel[3]?.valor).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('datosCobranza', () => {
|
||||
it('devuelve al corriente vs con vencidos', () => {
|
||||
expect(datosCobranza(resumen())).toEqual([
|
||||
{ nombre: 'Al corriente', valor: 4 },
|
||||
{ nombre: 'Con vencidos', valor: 2 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatos', () => {
|
||||
it('moneda MXN sin centavos', () => {
|
||||
expect(formatoMoneda(125000)).toBe('$125,000')
|
||||
})
|
||||
|
||||
it('porcentaje desde fracción', () => {
|
||||
expect(formatoPorcentaje(0.4)).toBe('40%')
|
||||
expect(formatoPorcentaje(0.333)).toBe('33.3%')
|
||||
})
|
||||
})
|
||||
119
apps/dashboards/src/lib/reportes.ts
Normal file
119
apps/dashboards/src/lib/reportes.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Tipos del endpoint GET /api/reportes/resumen y transformaciones puras para
|
||||
* las gráficas del tablero. Toda la lógica de forma de datos vive aquí para
|
||||
* probarla sin renderizar componentes.
|
||||
*/
|
||||
|
||||
export interface ResumenReportes {
|
||||
generadoEn: string
|
||||
leads: {
|
||||
total: number
|
||||
nuevosHoy: number
|
||||
nuevosSemana: number
|
||||
porEstado: Record<string, number>
|
||||
porOrigen: Record<string, number>
|
||||
}
|
||||
oportunidades: {
|
||||
total: number
|
||||
activas: number
|
||||
porEtapa: Record<string, number>
|
||||
tasaAparto: number
|
||||
tasaGanado: number
|
||||
}
|
||||
unidades: {
|
||||
total: number
|
||||
disponibles: number
|
||||
porDesarrollo: { desarrollo: string; total: number; porStatus: Record<string, number> }[]
|
||||
}
|
||||
cobranza: {
|
||||
planes: { activos: number; liquidados: number; cancelados: number }
|
||||
planesAlCorriente: number
|
||||
planesConVencidos: number
|
||||
pagosVencidos: number
|
||||
montoVencido: number
|
||||
}
|
||||
actividadesAbiertas: number
|
||||
}
|
||||
|
||||
// Status de inventario que se grafican por separado; el resto se agrupa en OTROS
|
||||
export const STATUS_UNIDAD = ['DISPONIBLE', 'APARTADO', 'VENDIDO', 'BLOQUEADO'] as const
|
||||
|
||||
export interface RenglonUnidades {
|
||||
desarrollo: string
|
||||
DISPONIBLE: number
|
||||
APARTADO: number
|
||||
VENDIDO: number
|
||||
BLOQUEADO: number
|
||||
OTROS: number
|
||||
}
|
||||
|
||||
/** Filas para la barras apiladas: unidades por desarrollo × status */
|
||||
export function unidadesApiladas(resumen: ResumenReportes): RenglonUnidades[] {
|
||||
return resumen.unidades.porDesarrollo.map((d) => {
|
||||
const renglon: RenglonUnidades = {
|
||||
desarrollo: d.desarrollo,
|
||||
DISPONIBLE: 0,
|
||||
APARTADO: 0,
|
||||
VENDIDO: 0,
|
||||
BLOQUEADO: 0,
|
||||
OTROS: 0,
|
||||
}
|
||||
for (const [status, n] of Object.entries(d.porStatus)) {
|
||||
if ((STATUS_UNIDAD as readonly string[]).includes(status)) {
|
||||
renglon[status as (typeof STATUS_UNIDAD)[number]] = n
|
||||
} else {
|
||||
renglon.OTROS += n
|
||||
}
|
||||
}
|
||||
return renglon
|
||||
})
|
||||
}
|
||||
|
||||
export interface EtapaFunnel {
|
||||
etapa: string
|
||||
valor: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Datos del funnel comercial: Leads → Oportunidades → Aparto o más → Ganado.
|
||||
* "Aparto o más" es acumulado (Aparto + Ganado) para que el funnel no suba.
|
||||
*/
|
||||
export function datosFunnel(resumen: ResumenReportes): EtapaFunnel[] {
|
||||
const porEtapa = resumen.oportunidades.porEtapa
|
||||
const conteo = (etapa: string): number =>
|
||||
Object.entries(porEtapa)
|
||||
.filter(([k]) => k.trim().toUpperCase() === etapa)
|
||||
.reduce((acc, [, v]) => acc + v, 0)
|
||||
const apartoOMas = conteo('APARTO') + conteo('GANADO')
|
||||
return [
|
||||
{ etapa: 'Leads', valor: resumen.leads.total },
|
||||
{ etapa: 'Oportunidades', valor: resumen.oportunidades.total },
|
||||
{ etapa: 'Aparto o más', valor: apartoOMas },
|
||||
{ etapa: 'Ganado', valor: conteo('GANADO') },
|
||||
]
|
||||
}
|
||||
|
||||
export interface Rebanada {
|
||||
nombre: string
|
||||
valor: number
|
||||
}
|
||||
|
||||
/** Rebanadas de la gráfica de cobranza: planes activos al corriente vs con vencidos */
|
||||
export function datosCobranza(resumen: ResumenReportes): Rebanada[] {
|
||||
return [
|
||||
{ nombre: 'Al corriente', valor: resumen.cobranza.planesAlCorriente },
|
||||
{ nombre: 'Con vencidos', valor: resumen.cobranza.planesConVencidos },
|
||||
]
|
||||
}
|
||||
|
||||
const formatoMXN = new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 })
|
||||
|
||||
/** Formato monetario MXN sin centavos: $1,250,000 */
|
||||
export function formatoMoneda(valor: number): string {
|
||||
return formatoMXN.format(valor)
|
||||
}
|
||||
|
||||
/** Fracción (0.4) a texto porcentaje (40%) */
|
||||
export function formatoPorcentaje(fraccion: number): string {
|
||||
return `${(fraccion * 100).toLocaleString('es-MX', { maximumFractionDigits: 1 })}%`
|
||||
}
|
||||
17
apps/dashboards/src/main.tsx
Normal file
17
apps/dashboards/src/main.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource/inter/300.css'
|
||||
import '@fontsource/inter/400.css'
|
||||
import '@fontsource/inter/500.css'
|
||||
import '@fontsource/inter/700.css'
|
||||
import './index.css'
|
||||
import AuthGate from './components/AuthGate'
|
||||
import DashboardPage from './pages/DashboardPage'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<AuthGate>
|
||||
<DashboardPage />
|
||||
</AuthGate>
|
||||
</StrictMode>,
|
||||
)
|
||||
227
apps/dashboards/src/pages/DashboardPage.tsx
Normal file
227
apps/dashboards/src/pages/DashboardPage.tsx
Normal file
@@ -0,0 +1,227 @@
|
||||
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,
|
||||
formatoMoneda,
|
||||
formatoPorcentaje,
|
||||
unidadesApiladas,
|
||||
type ResumenReportes,
|
||||
} from '../lib/reportes'
|
||||
import { fetchResumen } from '../services/reportes'
|
||||
|
||||
// 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']
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
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 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="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>
|
||||
|
||||
<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>
|
||||
)
|
||||
}
|
||||
77
apps/dashboards/src/services/auth.ts
Normal file
77
apps/dashboards/src/services/auth.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
// Sesión de autenticación contra el API Gateway (JWT guardado en localStorage)
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.10.123:3000/api'
|
||||
const STORAGE_KEY = 'frasa_auth'
|
||||
|
||||
export interface UsuarioSesion {
|
||||
nombre: string
|
||||
rol: string
|
||||
asignacion: string | null
|
||||
}
|
||||
|
||||
export interface Sesion {
|
||||
token: string
|
||||
usuario: UsuarioSesion
|
||||
}
|
||||
|
||||
/** Error de login con mensaje genérico (no filtra si el usuario existe) */
|
||||
export class ErrorLogin extends Error {
|
||||
constructor(message = 'Usuario o contraseña incorrectos') {
|
||||
super(message)
|
||||
this.name = 'ErrorLogin'
|
||||
}
|
||||
}
|
||||
|
||||
export function getSesion(): Sesion | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
const sesion = JSON.parse(raw) as Sesion
|
||||
if (typeof sesion?.token !== 'string' || !sesion.usuario) return null
|
||||
return sesion
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
return getSesion()?.token ?? null
|
||||
}
|
||||
|
||||
export function logout(): void {
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
|
||||
/** POST /auth/login; guarda token + usuario en localStorage */
|
||||
export async function login(username: string, password: string): Promise<UsuarioSesion> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${API_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
})
|
||||
} catch {
|
||||
throw new ErrorLogin('No se pudo conectar con el servidor')
|
||||
}
|
||||
if (!res.ok) throw new ErrorLogin()
|
||||
const data = (await res.json()) as Sesion
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({ token: data.token, usuario: data.usuario }))
|
||||
return data.usuario
|
||||
}
|
||||
|
||||
/**
|
||||
* Agrega Authorization: Bearer a un RequestInit si hay sesión.
|
||||
* Sin token devuelve el init tal cual (las llamadas siguen iguales que antes).
|
||||
*/
|
||||
export function conAuth(init: RequestInit = {}): RequestInit {
|
||||
const token = getToken()
|
||||
if (!token) return init
|
||||
return { ...init, headers: { ...(init.headers as Record<string, string>), Authorization: `Bearer ${token}` } }
|
||||
}
|
||||
|
||||
/** Si el API responde 401: cierra sesión y recarga para volver al login */
|
||||
export function manejar401(res: Response): void {
|
||||
if (res.status !== 401) return
|
||||
logout()
|
||||
if (typeof window !== 'undefined') window.location.reload()
|
||||
}
|
||||
18
apps/dashboards/src/services/reportes.ts
Normal file
18
apps/dashboards/src/services/reportes.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
// Cliente del endpoint de reportes del API Gateway (misma red, same-origin tras NGINX)
|
||||
import { conAuth, manejar401 } from './auth'
|
||||
import type { ResumenReportes } from '../lib/reportes'
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL ?? 'http://192.168.10.123:3000/api'
|
||||
|
||||
/** GET /reportes/resumen; lanza Error con mensaje legible si el API falla */
|
||||
export async function fetchResumen(): Promise<ResumenReportes> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${API_URL}/reportes/resumen`, conAuth())
|
||||
} catch {
|
||||
throw new Error('No se pudo conectar con el servidor')
|
||||
}
|
||||
manejar401(res)
|
||||
if (!res.ok) throw new Error(`El API respondió ${res.status}`)
|
||||
return (await res.json()) as ResumenReportes
|
||||
}
|
||||
22
apps/dashboards/tsconfig.app.json
Normal file
22
apps/dashboards/tsconfig.app.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
7
apps/dashboards/tsconfig.json
Normal file
7
apps/dashboards/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
19
apps/dashboards/tsconfig.node.json
Normal file
19
apps/dashboards/tsconfig.node.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts", "vitest.config.ts"]
|
||||
}
|
||||
9
apps/dashboards/vite.config.ts
Normal file
9
apps/dashboards/vite.config.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
// La app se sirve detrás de NGINX bajo el prefijo /dash
|
||||
export default defineConfig({
|
||||
base: '/dash/',
|
||||
plugins: [react(), tailwindcss()],
|
||||
})
|
||||
8
apps/dashboards/vitest.config.ts
Normal file
8
apps/dashboards/vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
// Config de tests separada para no mezclar los tipos de Vite y Vitest
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
},
|
||||
})
|
||||
@@ -2,9 +2,9 @@ import { describe, it, expect } from 'vitest'
|
||||
import { MODULOS } from './modulos'
|
||||
|
||||
describe('MODULOS', () => {
|
||||
it('expone los 4 módulos del ecosistema', () => {
|
||||
expect(MODULOS).toHaveLength(4)
|
||||
expect(MODULOS.map((m) => m.id)).toEqual(['cotizador', 'alta-clientes', 'cobranza', 'agente-ia'])
|
||||
it('expone los 5 módulos del ecosistema', () => {
|
||||
expect(MODULOS).toHaveLength(5)
|
||||
expect(MODULOS.map((m) => m.id)).toEqual(['cotizador', 'alta-clientes', 'cobranza', 'agente-ia', 'tableros'])
|
||||
})
|
||||
|
||||
it('cada módulo tiene nombre, descripción y URL válida', () => {
|
||||
@@ -21,6 +21,7 @@ describe('MODULOS', () => {
|
||||
expect(urls['alta-clientes']).toBe('/client/')
|
||||
expect(urls['cobranza']).toBe('/pay/')
|
||||
expect(urls['agente-ia']).toBe('/ai/')
|
||||
expect(urls['tableros']).toBe('/dash/')
|
||||
})
|
||||
|
||||
it('no hay ids ni URLs duplicadas', () => {
|
||||
|
||||
@@ -31,4 +31,10 @@ export const MODULOS: Modulo[] = [
|
||||
descripcion: 'Asistente IA con la base de conocimiento de Frasa',
|
||||
url: '/ai/',
|
||||
},
|
||||
{
|
||||
id: 'tableros',
|
||||
nombre: 'Tableros',
|
||||
descripcion: 'KPIs comerciales, inventario y cobranza en tiempo real',
|
||||
url: '/dash/',
|
||||
},
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user